Abs() stl in c++?

Hello guys ,

In the yesterdays lunch time problem : BFRIEND Problem - CodeChef

Here is my code where i was using unsingned long long int and it gave WA : CodeChef: Practical coding for everyone

And here is the same code which i did long long int which gave AC :
https://www.codechef.com/viewsolution/29204946

As no value becomes negative , why is this giving WA ?
Is it because i did abs() function ??

Someone please help me
Thanks
:slight_smile:

This is because the result of subtraction of two unsigned numbers is also unsigned number. But you may think that -5 is casted to 5 because the sign bit doesn’t matter, but it doesn’t work that way.
In binary signed int -1 is equivalent to unsigned int 4294967295.

Example code: Akt3F5 - Online C++0x Compiler & Debugging Tool - Ideone.com

Try doing the subtraction 0-1 by hand and you will find out that it all happens due to the carry bit.

 0000
-0001
------
 1111
------

Hope this helps :grinning:

2 Likes

I tried submitting your code with an assertion @line 18 here and it resulted in a SIGABRT, i.e. the assertion evaluated to false. So, there is the chance that y can be less than a or b. If you refer to this, you’ll find out that abs(y - b) and abs(y - a) evaluates to 0, which isn’t what you want. You may handle such operations like this. Hope this helps. :slight_smile:

2 Likes