简体   繁体   English

GCD 如果正数和负数

[英]GCD if positive and negative numbers

As mentioned here : gcd(a,b) = gcd(-a,b) = gcd(-a,-b) .正如这里提到的: gcd(a,b) = gcd(-a,b) = gcd(-a,-b) However when I use following code, I get different output for input being (-4,-8).但是,当我使用以下代码时,输​​入为 (-4,-8) 时得到不同的输出。

gcd(x,y) gives -4 wheras gcd(abs(x),abs(y)) gives 4. gcd(x,y)给出 -4 而gcd(abs(x),abs(y))给出 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;
}

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使用递归的 C++ 中的最大公分母

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM