Abs() stl in c++?

Hello guys ,

In the yesterdays lunch time problem : https://www.codechef.com/problems/BFRIEND

Here is my code where i was using unsingned long long int and it gave WA : https://www.codechef.com/viewsolution/29204927

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: https://ideone.com/Akt3F5

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