使用欧几里得算法识别两个值的最大公约数 (GCD)

Identify the greatest common divisor (GCD) of the two values using Euclid's Algorithm

本文关键字:两个 GCD 最大公约数 识别 几里 算法      更新时间:2023-10-16

我的程序向用户询问两个数字,然后我必须将这些数字传递给我的函数。我的功能应该是"使用欧几里得算法确定两个值的最大公约数(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;
}

老兄,再简单不过了…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

但你至少应该试着谷歌一下,伙计。div =)

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

找到了这个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;
}