![]() |
VOOZH | about |
Given a very large number N. The task is to find (1n + 2n + 3n + 4n) mod 5.
Examples:
Input: N = 4
Output: 4
(1 + 16 + 81 + 256) % 5 = 354 % 5 = 4
Input: N = 7823462937826332873467731
Output: 0
Approach: (1n + 2n + 3n + 4n) mod 5 = (1n mod ?(5) + 2n mod ?(5) + 3n mod ?(5) + 4n mod ?(5)) mod 5.
This formula is correct because 5 is a prime number and it is coprime with 1, 2, 3, 4.
Know about ?(n) and modulo of large number
?(5) = 4, hence (1n + 2n + 3n + 4n) mod 5 = (1n mod 4 + 2n mod 4 + 3n mod 4 + 4n mod 4) mod 5
Below is the implementation of the above approach:
4
Time Complexity: O(|N|), where |N| is the length of the string.
Auxiliary Space: O(1), since no extra space has been taken.