How does index*int in a for loop end up with zero as result?

TheOddCoder :

We tried just for fun to create a for loop like below. We assumed that the number we get would be very high but we got 0. Why is it 0 and not something big? We even tried it with a long because we thought it might be bigger than a int. Thanks in advance.

private static void calculate() {
    int currentSolution = 1;
    for (int i = 1; i < 100; i++) {
        currentSolution *= i;
    }
    System.out.println(currentSolution);
}
Bathsheba :

Your int is wrapping round to -2147483648 when it reaches +2147483647.

By an amazing coincidence1, a multiplication by zero is introduced into your product.

See for yourself: write

if (currentSolution == 0){
    // What is the value of i?
}

You'll need a BigInteger to evaluate 100!.


1 Really it's not that amazing: it's just that 100! has 232 as a factor.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=444652&siteId=1