Given a number n , find the first k digits of n ^ n | function to calculate first k digits of n ^ n ; take log10 of n ^ n . log10 ( n ^ n ) = n * log10 ( n ) ; We 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 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
< ? php function firstkdigits ( $ n , $ k ) { $ product = $ n * log10 ( $ n ) ; $ decimal_part = $ product - floor ( $ product ) ; $ decimal_part = pow ( 10 , $ decimal_part ) ; $ digits = pow ( 10 , $ k - 1 ) ; $ i = 0 ; return floor ( $ decimal_part * $ digits ) ; } $ n = 1450 ; $ k = 6 ; echo firstkdigits ( $ n , $ k ) ; ? >