Search code examples
javasum-of-digits

Unknown factor in answer


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));

}

}


Solution

  • 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.