VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-1n-2n-3n-4n-mod-5-set-2/

⇱ Find (1^n + 2^n + 3^n + 4^n) mod 5 | Set 2 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find (1^n + 2^n + 3^n + 4^n) mod 5 | Set 2

Last Updated : 11 Jul, 2025

Given a very large number N. The task is to find (1n + 2n + 3n + 4n) mod 5.
Examples: 
 

Input: N = 4 
Output:
(1 + 16 + 81 + 256) % 5 = 354 % 5 = 4
Input: N = 7823462937826332873467731 
Output:
 


 


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: 
 


Output: 
4

 

Time Complexity: O(|N|), where |N| is the length of the string.
Auxiliary Space: O(1), since no extra space has been taken.

Comment
Article Tags:
Article Tags: