GCD if positive and negative numbers

4.6k Views Asked by At

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;
}
2

There are 2 best solutions below

0
On

Your algorithm cannot cover all positive and negative numbers. Use the code below.

int gcd(int a, int b){
    a = abs(a);b = abs(b);
    if (a == 0)
        return b;
    if (b == 0)
        return a;
    if (a == b)
        return a;
    if (a > b)
        return gcd(a - b, b);
    return gcd(a, b - a);
}
0
On

You're not taking into account that the output range has a plus or minus sign in it which breaks your algorithm, it's asserting that negative numbers and positive numbers are to be treated as the positive integers. Formal set theory in discrete mathematics has a different jargon set for symbols that are incompatible with most programming languages.

Greatest Common Denominator in C++ using recursion

int GCD(int A,int B)
{
    if(A==0) return B;
    if(B==0) return A;
    A=abs(A);
    B=abs(B);
    if(A>B) return GCD(B,A);
    return GCD(B%A,A);
}