【问题标题】:Identify the greatest common divisor (GCD) of the two values using Euclid's Algorithm使用欧几里得算法确定两个值的最大公约数 (GCD)
【发布时间】:2013-04-11 00:33:53
【问题描述】:

我的程序要求用户输入两个数字,然后我必须将这些数字传递给我的函数。我的函数应该“使用欧几里得算法识别两个值的最大公约数 (GCD)。如果该值大于 1 且小于两个数字中的较小者,则返回 true。将引用调用参数设置为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;
}

【问题讨论】:

  • 请包含您已经编写的代码,并指出它的哪一部分给您带来了问题。
  • 我应该直接复制粘贴还是有什么具体的方法给你看?
  • @user2085305 尽你所能。 :)
  • 我正在尽我所能,我所知道的。其余的我必须学习,对吧?到目前为止,这就是我所拥有的,或者我所知道的部分。现在是我开始向你们学习并开始改进的部分。
  • 为了让您的代码保持简单,您应该注意,如果您完全删除这三行if ( b == 0 ) return a; else,您的函数不会改变。如果b == 0,它仍然会返回a

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


【解决方案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

但你至少应该尝试用谷歌搜索一些东西。 =)

【讨论】:

    【解决方案2】:

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

    找到了这个

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

    【讨论】:

      猜你喜欢
      • 2020-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-21
      • 2021-11-02
      相关资源
      最近更新 更多