简体   繁体   English

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

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

I'm trying to create a GCD (greatest common denominator) function using recursion.我正在尝试使用递归创建一个 GCD(最大公分母)function。 I cannot understand why it isn't working properly.我不明白为什么它不能正常工作。 For input 10 and 50 is returning 36.对于输入 10 和 50 返回 36。

Here's my code:这是我的代码:

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

Using a static variable is a problem because you use it in the form n * gcd(...) and the value of n shouldn't be the same than that used by the recursion.使用 static 变量是一个问题,因为您以n * gcd(...)的形式使用它,并且 n 的值不应与递归使用的值相同。 So you should pass a parameter instead.所以你应该传递一个参数。 You should also add a condition to stop when n becomes greater than the smaller term:您还应该添加一个条件以在 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);
}

the static variable is the cause for the error. static 变量是错误的原因。 In

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

n is evaluated after the recursion is called. n在调用递归之后计算。 So, as your recursion stops when you call gcd( 5/5, 25/5 ) and n is incremented to 6 by that call you just have 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因此,当您调用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