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
< ? php function power ( $ x , $ y , $ p ) { $ res = 1 ; while ( $ y > 0 ) { if ( $ y & 1 ) $ res = ( $ res * $ x ) % $ p ; $ x = ( $ x * $ x ) % $ p ; } return $ res ; } function numberOfDigits ( $ x ) { $ i = 0 ; while ( $ x ) { $ x = ( int ) $ x / 10 ; $ i ++ ; } return $ i ; } function printLastKDigits ( $ a , $ b , $ k ) { echo " Last ▁ " , $ k ; echo " ▁ digits ▁ of ▁ " , $ a ; echo " ^ " , $ b , " ▁ = ▁ " ; $ temp = 1 ; for ( $ i = 1 ; $ i <= $ k ; $ i ++ ) $ temp *= 10 ; $ temp = power ( $ a , $ b , $ temp ) ; for ( $ i = 0 ; $ i < $ k - numberOfDigits ( $ temp ) ; $ i ++ ) echo 0 ; if ( $ temp ) echo $ temp ; } $ a = 11 ; $ b = 3 ; $ k = 2 ; printLastKDigits ( $ a , $ b , $ k ) ; ? >