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 ; Method 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 prvar zeros ; If temp is not zero then print temp If temp is zero then already printed ; Driver Method
function power ( x , y , p ) { var res = 1 ; while ( y > 0 ) { if ( ( y & 1 ) != 0 ) res = ( res * x ) % p ; x = ( x * x ) % p ; } return parseInt ( res ) ; } function printLastKDigits ( a , b , k ) { document . write ( " " + k + " " + a + " " + b + " " ) ; var temp = 1 ; for ( i = 1 ; i <= k ; i ++ ) temp *= 10 ; temp = power ( a , b , temp ) ; for ( i = 0 ; i < k - temp . toString ( ) . length ; i ++ ) document . write ( 0 ) ; if ( temp != 0 ) document . write ( temp ) ; } var a = 11 ; var b = 3 ; var k = 2 ; printLastKDigits ( a , b , k ) ;