As mentioned here: gcd(a,b) = gcd(-a,b) = gcd(-a,-b)
. However when I use following code, I get different output for input being (-4,-8).
gcd(x,y)
gives -4 wheras gcd(abs(x),abs(y))
gives 4.
Can some one help me understand where I am wrong.
int gcd(int a ,int b)
{
if(b==0)
return a;
return gcd(b,a%b);
}
int main()
{
int x,y;
cin>>x>>y;
cout<<gcd(x,y)<<endl; // gives -4
cout<<gcd(abs(x),abs(y))<<endl; //gives 4
return 0;
}
Your algorithm cannot cover all positive and negative numbers. Use the code below.