c – Nested for loop, run series 10000 times
You have an integer overflow. Look, you define f as int
int i, f = 1;
and f grows fast and became huge, at the end it must have been (19!)^10000 (a quite big 19! raised into 10000 power); however, int value can not be greater than 2^31 - 1, and so the integer overflow comes (you can get negative values, then positive one, zero).
When i == 18, j == 1 it appears, that f == 0 and from now you have
// when i == 18, j = 1 we have f == 0 due to integer overflow
calculation += 1.00 / f;
equals to infinity.
Quick amendment is to declare f being float:
int i;
float f = 1.0;
The computation is still ineffcient, but the calculation is now valid.
calculation == 1.7182816
Edit: note, that f grows fast, at j = 2, i = 8 we have f == infinity. From now on we start doing nothing:
1.00 / infinity == 0
and that’s why
calculation += 1.00 / f;
equals to
calculation += 0;
We can well rewrite
// we don't want add 0 9997 times
for(int j=0; j<=10000; j++) ...
into (all we want is at most 4 outer loops instead of 10000)
for(int j=0; j<=3; j++) ...
Read more here: Source link
