Reputation: 5
can you please explain why this code is going in infinite loop? I am unable to find the error. It is working fine with small values of n and m.
#include<bits/stdc++.h>
using namespace std;
int main()
{
long long n=1000000, m=1000000;
long long k = 1;
for (long long i = 0; i < n; i++)
{
for (long long j = 0; j < m; j++)
{
k++;
}
}
cout << k;
return 0;
}
Upvotes: 0
Views: 237
Reputation:
when I Run this code I got this as my output
1000000000001
reference : I had run this code in the code chef IDE(https://www.codechef.com/ide) you can try in this IDE once, I guess there is some problem with your IDE or might be some other issue
it took me less than 20 sec to run this(on clock😁)
But when I put the same code in CODE::BLOCKS its taking long time(like you said infinite loops running) and the reason is quite simple it should do 1000000000000 runs
however this brings me a questions what's difference between code chef IDE and code::blocks compiler (Got a New question from your question 😁🤔(Difference Between Code-Chef IDE and Code::Blocks))
Finally answer is try on with code chef IDE that's it , this code runs fast there🤣
Hope this Helps you 😃
Upvotes: 0
Reputation: 536
It is a typical target for optimization.
g++ t_duration.cpp -Ofast -std=c++11 -o a_fast
#time ./a_fast
1000000000001
real 0m0.002s
user 0m0.000s
sys 0m0.002s
it takes almost no time to return the output.
g++ t_duration.cpp -O1 -std=c++11 -o a_1
#./a_1
419774 ms
About 420 seconds to complete the calculation.
Upvotes: 1
Reputation:
It's not infinite, but that k++
operation has to run for 1,000,000 * 1,000,000 = 1,000,000,000,000
times. It's not infinite, but it takes too long. That's exactly why it works well with small n and m values.
Upvotes: 1