Last digit of a number raised to last digit of N factorial | Java program for the above approach ; Function to find a ^ b using binary exponentiation ; Initialise result ; If b is odd then , multiply result by a ; b must be even now Change b to b / 2 ; Change a = a ^ 2 ; Function to find the last digit of the given equation ; To store cyclicity ; Store cyclicity from 1 - 10 ; Observation 1 ; Observation 3 ; To store the last digits of factorial 2 , 3 , and 4 ; Find the last digit of X ; Step 1 ; Divide a [ N ] by cyclicity of v ; If remainder is 0 ; Step 1.1 ; Step 1.2 ; Step 1.3 ; If r is non - zero , then return ( l ^ r ) % 10 ; Else return 0 ; Else return 1 ; Driver 's Code ; Given Numbers ; Function Call ; Print the result
import java . util . * ; class TestClass { public static long power ( long a , long b , long c ) { long result = 1 ; while ( b > 0 ) { if ( ( b & 1 ) = = 1 ) { result = ( result * a ) % c ; } b / = 2 ; a = ( a * a ) % c ; } return result ; } public static long calculate ( long X , long N ) { int a [ ] = new int [ 10 ] ; int cyclicity [ ] = new int [ 11 ] ; cyclicity [ 1 ] = 1 ; cyclicity [ 2 ] = 4 ; cyclicity [ 3 ] = 4 ; cyclicity [ 4 ] = 2 ; cyclicity [ 5 ] = 1 ; cyclicity [ 6 ] = 1 ; cyclicity [ 7 ] = 4 ; cyclicity [ 8 ] = 4 ; cyclicity [ 9 ] = 2 ; cyclicity [ 10 ] = 1 ; if ( N = = 0 N = = 1 ) { return ( X % 10 ) ; } else if ( N = = 2 N = = 3 N = = 4 ) { long temp = ( long ) 1e18 ; a [ 2 ] = 2 ; a [ 3 ] = 6 ; a [ 4 ] = 4 ; long v = X % 10 ; if ( v ! = 0 ) { int u = cyclicity [ ( int ) v ] ; int r = a [ ( int ) N ] % u ; if ( r = = 0 ) { if ( v = = 2 v = = 4 v = = 6 v = = 8 ) { return 6 ; } else if ( v = = 5 ) { return 5 ; } else if ( v = = 1 v = = 3 v = = 7 v = = 9 ) { return 1 ; } } else { return ( power ( v , r , temp ) % 10 ) ; } } else { return 0 ; } } return 1 ; } public static void main ( String args [ ] ) throws Exception { int X = 18 ; int N = 4 ; long result = calculate ( X , N ) ; System . out . println ( result ) ; } }