Question

Am trying to print the sum of digits in 2^n for n = 1 to 1000. Here's what I've done.

public static void main(String[] args) {
    int n = 1000;
    for (int i = 1; i < n; i++) {
        BigInteger power = BigInteger.valueOf((int)Math.pow(2, i));
        int sum = 0;
        while (power.intValue() > 0) {
            sum += power.intValue() % 10;
            power = power.divide(BigInteger.valueOf(10));
        }
        System.out.print(sum + "  ");
    }
}

It works only till about 2^30 or so and then prints the same result, 46, for the rest.

I tried a similar thing using "long long" in C and that printed 0's after a similar limit.

According to the answers, I changed

BigInteger power = BigInteger.valueOf((int)Math.pow(2, i));

to

BigInteger power = BigInteger.valueOf(2).pow(i);

and 46 changed to 0. Just like C. Still not working...

Was it helpful?

Solution

You're using Math.pow to generate the value you should use the BigInteger functions to do so instead.

The sum should be stored in a BigInteger as well not an int.

OTHER TIPS

You are doing integer arithmetic and then putting it into a biginteger. Use a biginteger's pow method instead.

Because you aren't using BigInteger.

Computing numbers using BigInteger doesn't let you magically store their sum in an int.

Similarly, passing an int to BigInteger.valueOf() doesn't magically make that int bigger.

You're calling Math.pow() with regular integers, not BigIntegers. You're calling it on integer literals.

You want this:

int i = 7; //or whatever power
BigInteger k = BigInteger.valueOf(2);
k = k.pow(i);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top