Nested for loop, run series 10000 times

Viewed 260

Could I ask for input on what I might be doing wrong, please. I am trying to run my inner for loop 10000 times, but after the first print out, I am getting infinity as the printed value.

#include <stdio.h>

int i, f = 1;
float calculation = 0;

int main()
{
    for(int j=0; j<=10000; j++)
    {
        for(i=1; i<=19; i++)
        {
            f = f * i;
            calculation += 1.00 / f;
        }

        printf("Factorial calculation is 1/ %d!=%f\n", i, calculation);
    }

    return 0;
}
1 Answers

You have an integer overflow. Look, you define f as int

 int i, f = 1;

and f grows fast and becomes huge, at the end it must have been (19!)^10000 (quite a 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 as 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++) ...
Related