Either this is something strangely deep or i have to revisit time complexity analysis for a piece of code !!
#include <iostream>
int main()
{
long long int t=1e18,a=0;
while(t--) a++;
std::cout<<a;
return 0;
}
This code executes in 15 ms codeforces / codechef ide! How is that even possible?
May be this question is too dumb but any help is appreciated. Thanks!
Codeforces will compile it with
-O2
, which means the code will be optimized. This code is so simple that even the compiler will figure out that all this really long while loop does is setsa
to $$$10^{18}$$$ andt
to 0.Yep, here's the proof — https://godbolt.org/z/d8fo-p
Thanks for your reply, need to look after these complier flags for now! Will the compiler be able to optimize it if i add branches here and there in the while block, like adding some if statements?
Probably not to something that runs in 15ms (or even $$$10^9$$$ seconds), unless these if-statements are very trivial (all clauses are always trivially true or trivially false, for example). It's really hard to automatically optimize programs to constant formulas like that.
Oh! Learnt something new today, though have seen these compiler flags in many snippets earlier but never knew what they actually did Thanks!