Md Zobayer Md Zobayer - 2 months ago 16
C++ Question

Why while(scanf("%lld", &num) == 1) is faster than while(scanf("%lld", &num))

I have tried to solve a problem from Uva Online Judge. Problem number is 10302. My accepted code is given below.

#include <cstdio>

int main()
{
long long int num, sum;

while(scanf("%lld", &num) == 1) {

//sumOfCube(sum, num);
//sum = (long long int)(num * num * (num + 1) * (num + 1)) / 4;
printf("%lld\n", ((num * num) * ((num + 1) * (num + 1))) / 4);
}

return (0);
}


And Here my time limit exceeded code

#include <cstdio>

int main()
{
long long int num, sum;


while(scanf("%lld", &num)) {

//sumOfCube(sum, num);
//sum = (long long int)(num * num * (num + 1) * (num + 1)) / 4;
printf("%lld\n", ((num * num) * ((num + 1) * (num + 1))) / 4);
}

return (0);
}


The only difference is

while(scanf("%lld", &num) == 1)


And

while(scanf("%lld", &num))


I think second one is faster. Because first one add extra operator
==
to check equality. Here Right hand side already
true (1)
and when
scanf()
takes an input then Left hand side is
true
. If both side is
true
then the
while
loop is true. I think it is an extra time loss.

But i can't understand why judge choose first one is faster.

Any one please explain it.

Answer

Your second version has an infinite loop.

scanf returns EOF (probably a macro for -1, though this depends on your system to some degree) when it runs out of input, and this return value is satisfying your very loose condition.

Your rationalisation about the second one being "faster" because you didn't write == 1 makes no sense (C++ is not executed one source code character at a time!), and this is a good example of why you should prefer to understand the logic rather than spending all your time attempting to micro-optimise instead.

Next time put some debug output in your code, or run your program through a debugger. You'll very quickly see what is going on.