Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

for-loop

int

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);
}
like image 600
TheOddCoder Avatar asked Aug 09 '17 07:08

TheOddCoder


1 Answers

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.

like image 179
Bathsheba Avatar answered Oct 08 '22 19:10

Bathsheba