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 ; Driver Code ; Given numbers ; Function call ; Print the result
def power ( a , b , c ) : NEW_LINE INDENT result = 1 NEW_LINE while ( b > 0 ) : NEW_LINE INDENT if ( ( b & 1 ) == 1 ) : NEW_LINE INDENT result = ( result * a ) % c NEW_LINE DEDENT b //= 2 NEW_LINE a = ( a * a ) % c NEW_LINE DEDENT return result NEW_LINE DEDENT def calculate ( X , N ) : NEW_LINE INDENT a = 10 * [ 0 ] NEW_LINE cyclicity = 11 * [ 0 ] NEW_LINE cyclicity [ 1 ] = 1 NEW_LINE cyclicity [ 2 ] = 4 NEW_LINE cyclicity [ 3 ] = 4 NEW_LINE cyclicity [ 4 ] = 2 NEW_LINE cyclicity [ 5 ] = 1 NEW_LINE cyclicity [ 6 ] = 1 NEW_LINE cyclicity [ 7 ] = 4 NEW_LINE cyclicity [ 8 ] = 4 NEW_LINE cyclicity [ 9 ] = 2 NEW_LINE cyclicity [ 10 ] = 1 NEW_LINE if ( N == 0 or N == 1 ) : NEW_LINE INDENT return ( X % 10 ) NEW_LINE DEDENT elif ( N == 2 or N == 3 or N == 4 ) : NEW_LINE INDENT temp = 1e18 ; NEW_LINE a [ 2 ] = 2 NEW_LINE a [ 3 ] = 6 NEW_LINE a [ 4 ] = 4 NEW_LINE v = X % 10 NEW_LINE if ( v != 0 ) : NEW_LINE INDENT u = cyclicity [ v ] NEW_LINE r = a [ N ] % u NEW_LINE if ( r == 0 ) : NEW_LINE INDENT if ( v == 2 or v == 4 or v == 6 or v == 8 ) : NEW_LINE INDENT return 6 NEW_LINE DEDENT elif ( v == 5 ) : NEW_LINE INDENT return 5 NEW_LINE DEDENT elif ( v == 1 or v == 3 or v == 7 or v == 9 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT return ( power ( v , r , temp ) % 10 ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT return 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X = 18 NEW_LINE N = 4 NEW_LINE result = calculate ( X , N ) NEW_LINE print ( result ) NEW_LINE DEDENT