Search code examples
javabigintegerfactorial

Find the sum of the digits in the number 100! (My while loop would not stop)


I've been trying to solve Problem 20 in Project Euler:

n! means n (n 1) ... 3 * 2 * 1 For example, 10! = 10 * 9 ... 3 * 2 * 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100!

This is what I came up with so far. I already got the correct answer (which was 648) with this code, but I got a bit OC, because my code is an infinite loop. After the result became 0 inside the while loop, it just wouldn't stop. Can anybody help me fix this?

public static BigInteger problem20(int max){
    BigInteger sum = BigInteger.valueOf(0);
    BigInteger result = BigInteger.valueOf(1);
    BigInteger currentNum = BigInteger.valueOf(0);

    for(long i = 1; i<=max; i++){
        result  = result.multiply(BigInteger.valueOf(i));
        //System.out.println(result);
    }

    while (!result.equals(0)) {
        sum = sum.add(result.mod(BigInteger.valueOf(10)));
        result = result.divide(BigInteger.valueOf(10));
        System.out.println(sum + " "+ result);
    }
    return sum;
}

Solution

  • This is the problem:

    while (!result.equals(0))
    

    result is a BigInteger, which will never be equal to an Integer. Try using

    while (!result.equals(BigInteger.ZERO))