-1

I can't find the problem with what I wrote. I am attempting Project Euler #16, where I need to sum all digits of 2^1000. My program works with small numbers, but as numbers get around 18 digits or so, it breaks. Any help?

public static double digit(double n){

    return n % 10;

}

public static double sumofDigits(double n){

    double sum = 0;

    while(n > 1){

        sum += digit(n);
        n = Math.floor(n/10);

    }

    return sum;

}

public static void main(String[] args) {

    double x = Math.pow(2,1000);

    double y = 22222222222222222222d;

    System.out.println(sumofDigits(x));

            System.out.println(sumofDigits(y));

}

}

Brian
  • 167
  • 1
  • 9

3 Answers3

5

A double has an accuracy of about 16 decimal digits. Since 2 power 1000 has much more digits (about 300) you simply can not work with a double.

Have a look at the BigInteger class.

Henry
  • 42,982
  • 7
  • 68
  • 84
1

You cannot use double here: they have a limited precision only. (see Java primitive datatypes)

So Math.pow(2,1000)only computes some (first) digits and the exponent.

You have to use some library which handles arbitrary long integers. (e.g. biginteger)

Andreas Florath
  • 4,418
  • 22
  • 32
0

I got it now. I've replaced all the doubles here with a BigDecimal object representing that decimal number so that decimal accuracy && size of # is achieved. Thanks everyone.

Brian
  • 167
  • 1
  • 9