Find ( 1 ^ n + 2 ^ n + 3 ^ n + 4 ^ n ) mod 5 | Set 2 | Java implementation of the approach ; Function to return A mod B ; length of the string ; to store required answer ; Function to return ( 1 ^ n + 2 ^ n + 3 ^ n + 4 ^ n ) % 5 ; Calculate and return ans ; Driver code
class GFG { static int A_mod_B ( String N , int a ) { int len = N . length ( ) ; int ans = 0 ; for ( int i = 0 ; i < len ; i ++ ) ans = ( ans * 10 + ( int ) N . charAt ( i ) - '0' ) % a ; return ans % a ; } static int findMod ( String N ) { int mod = A_mod_B ( N , 4 ) ; int ans = ( 1 + ( int ) Math . pow ( 2 , mod ) + ( int ) Math . pow ( 3 , mod ) + ( int ) Math . pow ( 4 , mod ) ) ; return ( ans % 5 ) ; } public static void main ( String args [ ] ) { String N = "4" ; System . out . println ( findMod ( N ) ) ; } }