Last digit of a number raised to last digit of N factorial | 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 ; Given Numbers ; Function Call ; Print the result
function power ( a , b , c ) { var result = 1 ; while ( b > 0 ) { if ( ( b & 1 ) == 1 ) { result = ( result * a ) % c ; } b /= 2 ; a = ( a * a ) % c ; } return result ; } function calculate ( X , N ) { var a = [ ... Array ( 10 ) ] ; var cyclicity = [ ... Array ( 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 ) { var temp = 1e18 ; a [ 2 ] = 2 ; a [ 3 ] = 6 ; a [ 4 ] = 4 ; var v = X % 10 ; if ( v != 0 ) { var u = cyclicity [ parseInt ( v ) ] ; var r = a [ parseInt ( 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 ; } var X = 18 ; var N = 4 ; var result = calculate ( X , N ) ; document . write ( result ) ;