I was solving a question on gcd : (https://codeforces.com/contest/798/problem/C). here the inbuild function of gcd in c++ i.e __gcd(a,b) gives the wrong answer. the gcd of -2 and 4 should be 2. but inbuild function in sublime gives answer -2. can anyone explain why? later when i searced i founded that __gcd(a,b) == __gcd(|a|,|b|) but there is no where written that you only have to pass non negative number in GCD funtion in c++. thank you in advance.
As i am newbie please don't just do downvote and go. if you cannot help atleast don't downvote. I am learning things. and it will take some time for me to learn and reach red
Some functions with negative number can work strange in C++ (gcd, %). In case of gcd, i recommend to use function abs() if negative numbers are possible.
It depends on the compiler, you also face such kind of problem in the inbuilt power function of c++
can you please let me know the problems in inbuild power function so that i can be extra carefull while using the function
You can refer this blog https://codeforces.com/blog/entry/1521
The implementation might differ depending on compiler, but this is the implementation of
__gcd
in MinGW 10.2.0 for example:As you can see, the implementation doesn't care about positives or negatives. If you trace the code for your specific input, you'll see why it's -2.
If you want to get the abs of the answer, use
std::gcd
in C++17 instead.i am using c++17 only. still getting that answer
That's because you are using
__gcd(a,b)
instead ofgcd(a,b)
.Try to use
gcd
instead of__gcd
:Output: