Find the first and last M digits from K | Python3 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
from math import * NEW_LINE def modPower ( a , b , M ) : NEW_LINE INDENT res = 1 NEW_LINE while ( b ) : NEW_LINE INDENT if ( b & 1 ) : NEW_LINE INDENT res = res * a % M NEW_LINE DEDENT a = a * a % M NEW_LINE b >>= 1 NEW_LINE DEDENT return res NEW_LINE DEDENT def findFirstAndLastM ( N , K , M ) : NEW_LINE INDENT lastM = modPower ( N , K , int ( pow ( 10 , M ) ) ) NEW_LINE firstM = 0 NEW_LINE y = K * log10 ( N * 1.0 ) NEW_LINE y = y - int ( y ) NEW_LINE temp = pow ( 10.0 , y ) NEW_LINE firstM = int ( temp * pow ( 10 , M - 1 ) ) NEW_LINE print ( firstM , lastM ) NEW_LINE DEDENT N = 12 NEW_LINE K = 12 NEW_LINE M = 4 NEW_LINE findFirstAndLastM ( N , K , M ) NEW_LINE