Search code examples
javaalgorithmsum-of-digits

Sum of digits issue


I'm doing some problems of Project Euler and I've stumbled upon an issue. I have no idea why this algorithm doesn't work for 2^1000. It works for numbers in the range of 10^1 and 10^8 (Those are the ones I tested), but it should work for every possible range.

2^1000 is 1.07*10^301 by the way. The upper limit of a double lies at more or less 10^308 so the number is still in range.

import java.lang.Math;

public class Euler15 {
    public static void main(String[] args) {


        int count = 0;
        double res = Math.pow(2,1000);

        for(int i = 301; i >= 0; i--){
            if (res == 0){
                break;
            }
            while (res >= Math.pow(10, i)){
                res-= Math.pow(10, i);
                System.out.println(res);
                count++;
            }
        }

    System.out.println(count);
}
}

Solution

  • 2^1000 is way to big for normal data types. Use BigInteger or strings.

    import java.math.BigInteger;
    

    Take an input as a BigInteger:

    BigInteger n = BigInteger.valueOf(2);
    

    Now power it up to 1000:

    n = n.pow(1000);
    

    Now, convert it into a string using toString() and then, add each character to your result, changing it to an int. That ought to do it.