使用递归函数的两个数字的GCD - 什么是错的?

时间:2012-07-11 12:58:49

标签: c

  

我是编程新手,只是一名学生。

我编写了一个使用递归函数计算两个数字的GCD的程序,但是它为一些人提供了正确的答案,而对于其他一些人给出了错误的答案。请帮助我找出问题所在:

#include<stdio.h>
#include<conio.h>

int gcd(int,int,int)

int main(){
    int a,b,x,val;
    printf("Enter the first number: ");
    scanf("%d",&a);
    printf("Enter the second number: ");
    scanf("%d",&b);

    if(a>b)
        x=b;
    else
        x=a;

    val=gcd(a,b,x);
    printf("The GCD of the two numbers you entered is:%d",val);
    getch();
    return 0;
}

int gcd(int a,int b,int x){
    if(a%x==0){
        if (b%x==0)
            return x;
    }else
        return gcd(a,b,x-1);
}

例如,当第一个数字= 69,第二个数字= 65时,程序给出错误答案,而在其他一些情况下,它会神秘地给出正确的答案。

有人可以帮助我吗?

4 个答案:

答案 0 :(得分:1)

检查您的代码路径。并非所有条件都在gcd函数中返回一个整数。 你使用的是哪个编译器?它应该给你一个警告或错误。

答案 1 :(得分:1)

试试这个:

int gcd(int a,int b,int x){
    if(a%x==0 && b%x==0) return x;        
    }else return gcd(a,b,x-1);
}

这在一个if语句中捕获模数比较为0,所有条件都不属于此get gcd调用。

答案 2 :(得分:0)

示例:考虑数字a=100b=44。当它达到x=25时,除以100,而不是44,您的代码没有正确的路径。

您没有考虑所有条件(路径)。

int gcd(int a,int b,int x){
    if(a%x==0){
        if (b%x==0)
           return x;
        else
           // ERROR ERROR ERROR, 
           // if the code reaches here, then it neither calls gcd recursively, 
           // nor does it return anything valueable
    }else
        return gcd(a,b,x-1);
}

您应该更改以下代码。

int gcd(int a,int b,int x){        
    if(a%x==0)
        if (b%x==0)
        {
            return x;
        }
    return gcd(a,b,x-1);
}

OR

int gcd(int a,int b,int x){
    if(a%x==0 && b%x==0) return x;        
    return gcd(a,b,x-1);
}

答案 3 :(得分:0)

C中两个数字的GCD(最简单的方法):

while(secNum != 0) {
    Temp = fNum % secNum;
    fNum = secNum;
    secNum = Temp;
}

printf("GCD of the given two numbers : %d",fNum);
相关问题