Find the first and last M digits from K | 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
function modPower ( a , b , M ) { var res = 1 ; while ( b ) { if ( b & 1 ) res = res * a % M ; a = a * a % M ; b >>= 1 ; } return res ; } function findFirstAndLastM ( N , K , M ) { var lastM = modPower ( N , K , Math . pow ( 10 , M ) ) ; var firstM ; var y = K * Math . log10 ( N * 1.0 ) ; y = y - parseInt ( y ) ; var temp = Math . pow ( 10.0 , y ) ; firstM = temp * Math . pow ( 10 , M - 1 ) ; document . write ( parseInt ( firstM ) + " " + parseInt ( lastM ) ) ; } var N = 12 , K = 12 , M = 4 ; findFirstAndLastM ( N , K , M ) ;