Find the first and last M digits from K | Java 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
class GFG { static long modPower ( long a , long b , long M ) { long res = 1 ; while ( b > 0 ) { if ( b % 2 == 1 ) res = res * a % M ; a = a * a % M ; b >>= 1 ; } return res ; } static void findFirstAndLastM ( long N , long K , long M ) { long lastM = modPower ( N , K , ( 1L ) * ( long ) Math . pow ( 10 , M ) ) ; long firstM ; double y = ( double ) K * Math . log10 ( N * 1.0 ) ; y = y - ( long ) y ; double temp = Math . pow ( 10.0 , y ) ; firstM = ( long ) ( temp * ( 1L ) * Math . pow ( 10 , ( M - 1 ) ) ) ; System . out . print ( firstM + " ▁ " + lastM + "NEW_LINE"); } public static void main ( String [ ] args ) { long N = 12 , K = 12 , M = 4 ; findFirstAndLastM ( N , K , M ) ; } }