Print last k digits of a ^ b ( a raised to power b ) | C ++ code to find last k digits of a ^ 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 ; C ++ function to calculate number of digits in x ; C ++ 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 program to test above functions
#include <iostream> NEW_LINE using namespace std ; int power ( long long int x , long long int y , long long int p ) { long long int res = 1 ; while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % p ; x = ( x * x ) % p ; } return res ; } int numberOfDigits ( int x ) { int i = 0 ; while ( x ) { x /= 10 ; i ++ ; } return i ; } void printLastKDigits ( int a , int b , int k ) { cout << " Last ▁ " << k ; cout << " ▁ digits ▁ of ▁ " << a ; cout << " ^ " << b << " ▁ = ▁ " ; int temp = 1 ; for ( int i = 1 ; i <= k ; i ++ ) temp *= 10 ; temp = power ( a , b , temp ) ; for ( int i = 0 ; i < k - numberOfDigits ( temp ) ; i ++ ) cout << 0 ; if ( temp ) cout << temp ; } int main ( ) { int a = 11 ; int b = 3 ; int k = 2 ; printLastKDigits ( a , b , k ) ; return 0 ; }