Print last k digits of a ^ b ( a raised to power b ) | Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; Initialize result ; x = x % p Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 y = y / 2 ; function to calculate number of digits in x ; function to print last k digits of a ^ b ; Generating 10 ^ k ; Calling modular exponentiation ; Printing leftmost zeros . Since ( a ^ b ) % k can have digits less then k . In that case we need to print zeros ; If temp is not zero then print temp If temp is zero then already printed ; Driver Code
def power ( x , y , p ) : NEW_LINE INDENT res = 1 NEW_LINE while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % p NEW_LINE DEDENT x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT def numberOfDigits ( x ) : NEW_LINE INDENT i = 0 NEW_LINE while ( x ) : NEW_LINE INDENT x //= 10 NEW_LINE i += 1 NEW_LINE DEDENT return i NEW_LINE DEDENT def printLastKDigits ( a , b , k ) : NEW_LINE INDENT print ( " Last ▁ " + str ( k ) + " ▁ digits ▁ of ▁ " + str ( a ) + " ^ " + str ( b ) , end = " ▁ = ▁ " ) NEW_LINE temp = 1 NEW_LINE for i in range ( 1 , k + 1 ) : NEW_LINE INDENT temp *= 10 NEW_LINE DEDENT temp = power ( a , b , temp ) NEW_LINE for i in range ( k - numberOfDigits ( temp ) ) : NEW_LINE INDENT print ( "0" ) NEW_LINE DEDENT if ( temp ) : NEW_LINE INDENT print ( temp ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 11 NEW_LINE b = 3 NEW_LINE k = 2 NEW_LINE printLastKDigits ( a , b , k ) NEW_LINE DEDENT