Given a number n , find the first k digits of n ^ n | function that manually calculates n ^ n and then removes digits until k digits remain ; take log10 of n ^ n . log10 ( n ^ n ) = n * log10 ( n ) ; We will now try to separate the decimal and integral part of the / product . The floor function returns the smallest integer less than or equal to the argument . So in this case , product - floor ( product ) will give us the decimal part of product ; we will now exponentiate this back by raising 10 to the power of decimal part ; We now try to find the power of 10 by which we will have to multiply the decimal part to obtain our final answer ; Driver code
function firstkdigits ( n , k ) { let product = n * Math . log10 ( n ) ; let decimal_part = product - Math . floor ( product ) ; decimal_part = Math . pow ( 10 , decimal_part ) ; let digits = Math . pow ( 10 , k - 1 ) , i = 0 ; return ( Math . floor ( decimal_part * digits ) ) ; } let n = 1450 ; let k = 6 ; document . write ( firstkdigits ( n , k ) ) ;