使用Euclid算法识别两个值的最大公约数(GCD)

时间:2013-04-11 00:33:53

标签: c++ greatest-common-divisor pass-by-reference call-by-value

我的程序要求用户输入两个数字,然后我必须将这些数字传递给我的函数。我的函数应该是“使用Euclid算法识别两个值的最大公约数(GCD)。如果该值大于1且小于两个数值中的较小值,则返回true。将call-by-reference参数设置为GCD的值。在main()输出GCD以及你的函数是否返回true或false。我该怎么做?

int gcd (int a, int b)
{
    int c;

    if ( b == 0 )
        return a;

    else
        while ( b != 0 )
        {
            c = b;
            b = a % b;
            a = c;
        }

        return a;
}

2 个答案:

答案 0 :(得分:1)

老兄,这不可能更简单...... STFG

您的代码已接近示例2,但此行中有错误

   if ( b == 0 )
        return a;

检查和返回应该是相反的顺序

我会在伪代码中尝试这个wiki实现:

function gcd(a, b)
    while b ≠ 0
       t := b
       b := a mod t
       a := t
    return a

但你应该至少尝试谷歌一些人。 =)

答案 1 :(得分:0)

这是你使用的最难的逻辑,你可以从博客中获得非常简单的逻辑,我从

找到了这个逻辑

http://www.programmingtunes.com/finding-greatest-common-divisor-of-2-numbers-c/

//greatest common divisor of 2 numbers in C++
#include <iostream>
using namespace std;
void main()
{
int x = 24;
int y = 18;
int temp = 1 ;
for(int i = 2; i<=y; i++)
{
    if(x%i == 0 && y%i == 0)
    {
    temp = i;
    }

}

cout<<temp<<endl;

}
相关问题