LuckyTuvshee
LuckyTuvshee

Reputation: 1194

How calculate number higher than limit, and use BigInteger

Below code calculates the sum of digits of 2^15 and working. If I change for loop condition to 15, d2 becomes 2^16. --> I want 2^15. Then I change it to 999, the sum of digits didn't match. (Sum: 1189)

Is there another way to do it?

public void go()
{           
    int sum = 0;
    BigInteger d2 = BigInteger.ONE.add(BigInteger.ONE);
    BigInteger two = d2;

    for(int i = 0; i < 14; i++)
    {
        System.out.println(d2);
        d2 = d2.multiply(two);
    }

    System.out.println("\n" + d2);

    double val = d2.doubleValue();
    double temp = val;
    while(val > 0)
    {
        temp = val % 10;
        val /= 10;
        sum += temp;
        System.out.println(temp);
    }

    System.out.println("Sum: " + sum);

}

Upvotes: 0

Views: 51

Answers (1)

Alex M
Alex M

Reputation: 915

You switch to double to calculate the sum of digits, when it looks like BigInteger.divideAndRemainder is what you need.

You would get something like:

temp = d2;

while (temp.compareTo(BigInteger.ZERO) > 0) {           
    BigInteger[] divideAndRemainder = temp.divideAndRemainder(BigInteger.valueOf(10));
    temp = divideAndRemainder[0];
    sum = sum.add(divideAndRemainder[1]);
}

Upvotes: 1

Related Questions