I am a novice to programming and computing.
I am running a C++ based program that is taking approx 6 hours on this machine. I use the timing utility of the framework I work in.
I tried calculating the total number of iterations of my nested loop via a simple program:
{
int k=0;
for (int i = 0; i < 196779; i++)
for (int j= i+1; j< 196779; j++)
{
k++;
if((k+1)%10000 == 0)
cout<< "\n Number of Instructions: " << k;
}
cout<< "\n Total Number of iterations = " << k << endl;
}
Mathematically I would expect it to agree with the value 1.9360889031 × 10^10 , which is the total number of 2-element subsets. I inserted that cout statement to see if something funny was happening, and indeed it does.
- The outpute exceeds the mathematically expected value. Is my calculation wrong?
- The output goes into negative values after a while as it exceeds the int range, but it shouldn’t.
Sample output at the end where I manually break
Number of Instructions: -2078590001
Number of Instructions: -2078580001
Number of Instructions: -2078570001
Number of Instructions: -2078560001
I found out the range of Int to be 2147483647, but I had made the calculations and concluded that my k should never exceed the limit. So where is the problem?
1.9360889031 × 10^10 (19,360,889,031) is larger than 2,147,483,647, the maximum value representable by an
int(at least on your compiler).You can use an
unsigned int, which correctly “rolls over” when a computation yields a value too large to be represented (or a negative value). When you overflow anint, you get undefined behavior.