Find the first and last M digits from K | C ++ Program to implement the above approach ; Function to find a ^ b modulo M ; Function to find the first and last M digits from N ^ K ; Calculate Last M digits ; Calculate First M digits ; Extract the number after decimal ; Find 10 ^ y ; Move the Decimal Point M - 1 digits forward ; Print the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE #define ll  long long int NEW_LINE using namespace std ; ll modPower ( ll a , ll b , ll M ) { ll res = 1 ; while ( b ) { if ( b & 1 ) res = res * a % M ; a = a * a % M ; b >>= 1 ; } return res ; } void findFirstAndLastM ( ll N , ll K , ll M ) { ll lastM = modPower ( N , K , ( 1LL ) * pow ( 10 , M ) ) ; ll firstM ; double y = ( double ) K * log10 ( N * 1.0 ) ; y = y - ( ll ) y ; double temp = pow ( 10.0 , y ) ; firstM = temp * ( 1LL ) * pow ( 10 , M - 1 ) ; cout << firstM << " ▁ " << lastM << endl ; } int main ( ) { ll N = 12 , K = 12 , M = 4 ; findFirstAndLastM ( N , K , M ) ; return 0 ; }