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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With