0

Following is the code that I wrote for finding the first k digits of n^n in Java

private static int firstK(int n,int k)
{
   double x, y;
   x = n * Math.log10(n);
   y = Math.floor(Math.pow(10, x - Math.floor(x) + k - 1));
   return((int)y);
}

However when I input n=99999999 and k=9 the result in Java comes out to be 367879457 however the original answer is supposed to be 367879443. Why is it displaying wrong result? Has it got anything to do with the precision of double in Java? Using BigDecimal gives the same result. Any suggestions on the code? BTW n<=10^9 and k<=9.

user2627317
  • 89
  • 1
  • 2
  • 9

1 Answers1

0

A double has about 16 decimal digits of accuracy. x is approximately 8e8, so when you compute x - Math.floor(x) (the fractional part), you get a number that's only accurate to about 7 or 8 digits. So the result can't be accurate to more than 8 digits.

Derek Ledbetter
  • 4,675
  • 3
  • 20
  • 18