2

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;
}
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
danish sodhi
  • 1,793
  • 4
  • 21
  • 31

2 Answers2

1

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);
}
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
google user
  • 49
  • 1
  • 1
  • 5
1

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);
}
Adrian W
  • 4,563
  • 11
  • 38
  • 52