Solution correct in C++ but giving wrong answer in C

My two solutions are of same logic but one is written in C and other in C++.
I just replaced scanf with cin and printf with cout and my code worked.
What could be the reasons?

C++ solution: https://www.codechef.com/viewsolution/15059386

C solution: https://www.codechef.com/viewsolution/15059456

Question link: https://www.codechef.com/problems/CHEFMOVR

1 Like

Be careful of format specifiers dear.

Replace those “%lli” with “%lld” and you will get AC in C solution as well.

Okay I have figured it out. The problem is not with the format specifier, %lli and %lld behave the same here. The real reason is this.

The abs() function you call in C only deals with int type. Bonus fact: this function is not in math.h (it is in stdlib.h), but your program is able to access it because it is a built-in function in GCC. (Link to man page)

The std::abs() function you call in C++ is overloaded for long int and long long int types. (Link to documentation)

You can see the abs() function return wrong values for this test case here. So in summary, when using C you should be using llabs to get the absolute value of a long long int type and not abs. Please correct me if I am wrong, this is quite a tricky business :stuck_out_tongue:

2 Likes

The problem is with function abs(). In C, only the int version exists. For the long int equivalent see labs. For the long long int equivalent see llabs.

That is strange. According to these answers, both %lli and %lld should give identical results.
Maybe there is some fault in the test case. For example a leading zero would cause scanf with %lli to interpret it as octal.

Yes, even I am surprised because both should had done the same thing.

What I did was, copy paste his C code, change lli to lld and submit it. I got Ac, but note that i submitted it in c++14 instead of C (i dont think it shld make any diff.) . What do you think meooow?

Yep, C and C++ made the difference :smiley:

#Shakti Billi’

This is the right reason. I also faced the same problem in a different question. One must know everything about a predefined function before using it.

1 Like