繁体   English   中英

我的递归最大公分母 function 工作不正常

[英]My recursive greatest common denominator function isn't working properly

我正在尝试使用递归创建一个 GCD(最大公分母)function。 我不明白为什么它不能正常工作。 对于输入 10 和 50 返回 36。

这是我的代码:

int main()
{
    printf("Rez=%d ", gcd(10,50));
    return 0;
}

int gcd(int a, int b)
{
    static int n=0;
    int result=1;
    n++;
    if(a<=1 || b<=1)
        return 1;
    else
    {
        if(a%n==0 && b%n==0)
            result=n* gcd(a/n,b/n);
        else
            gcd(a,b);
    }
    return result;
}

使用 static 变量是一个问题,因为您以n * gcd(...)的形式使用它,并且 n 的值不应与递归使用的值相同。 所以你应该传递一个参数。 您还应该添加一个条件以在 n 大于较小项时停止:

#include <stdio.h>

int main()
{
    printf("%d\n", gcd(10, 50, 1)); //==>10
    printf("%d\n", gcd(7, 35, 1));  //==>7
    printf("%d\n", gcd(8, 22, 1));  //==>2
    printf("%d\n", gcd(49, 5, 1));  //==>1
    printf("%d\n", gcd(0, 0, 1));   //==>1
    printf("%d\n", gcd(4, 2, 0));   //==>0
    return 0;
}

int gcd(int a, int b, int n)
{
    if (n <= 0) return 0;
    if (n > (a < b ? a : b) || a<=1 || b<=1) return 1;
    else if(a%n==0 && b%n==0) return n * gcd(a/n, b/n, n+1);
    else return gcd(a, b, n+1);
}

static 变量是错误的原因。

result=n* gcd(a/n,b/n);

n在调用递归之后计算。 因此,当您调用gcd( 5/5, 25/5 )时递归停止并且n通过该调用递增到 6,您只需 6 * gcd( 10/1, 50/1 ) = 6 * 6 * gcd( 10/2, 50/2) = 6 * 6 * 6 = gcd(5/5, 25/5) = 6 * 6 * 6 * 1 = 216

暂无
暂无

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

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