【问题标题】:Greatest Common Divisor using Euclidian Algorithm?使用欧几里得算法的最大公约数?
【发布时间】:2015-10-19 20:13:32
【问题描述】:

所以我的代码有问题。

我正在使用欧几里得算法编写一个最大公约数,我似乎无法利用循环来保持除法不断重复,直到我得到最大公约数。所以现在,我能够得到剩余的,但基本上不知道如何从那里继续。

任何帮助将不胜感激!

这是我目前所拥有的

#include <iostream>
#include <string>
#include <cmath>

using namespace std;

int a;//Holds the first number
int b;//Holds the second number
int temp;//Assign to greatest number
int hold;//Assign to smaller number
float euclid;//soon to be function?
int leftover;
float gcd;



int main ()
{
    cout<<"Welcome to Brian Garnadi's Version of GCD!\n"<<endl;
    cout<<"Enter the first integer to be calculated: ";
    cin>> a;
    cout<<"Now enter the second integer: ";
    cin>>b;

    if (a>b)//Determines bigger number
    {temp=a;
        hold=b;
    }
    if (a<b)//Determines smaller number
    {
        temp=b;
        hold=a;
    }

    leftover= temp%hold;

    cout<<"\nThe remainder of the two numbers divided is "<<leftover<<".\n"<<endl;

}

【问题讨论】:

  • 我在示例代码中没有看到循环。如果 (a > b),那么只需交换 a 和 b。不需要第二个 if。
  • 如果 a = b,您的代码也会失败

标签: c++ algorithm division greatest-common-divisor


【解决方案1】:

实际上没有必要计算更大的数字,欧几里得的算法自己管理。 这是工作代码:

#include <iostream>
using namespace std;
int gcd(int m,int n)
{
    if(n == 0)
        return m;
    return gcd(n, m % n);
}

int main()
{
    int a,b,answer;
    cout<<"Welcome to Brian Garnadi's Version of GCD!\n"<<endl;
    cout<<"Enter the first integer to be calculated: ";
    cin>> a;
    cout<<"Now enter the second integer: ";
    cin>>b;
    answer = gcd(a,b);
    cout << "The GCD of the two numbers is : " << answer << endl;
    return 0;
}

【讨论】:

  • 请尝试理解算法和代码。如果不清楚,请通过评论告诉我。
  • 我没有处理任何负数情况。如果你愿意,你可以做到,实现它应该很容易。
【解决方案2】:

不要忘记在算法中处理负数。

gcd(m, n) = gcd(n, m%n)   when n != 0
          = m             when n = 0

功能:

int gcd(int m, int n) {
    if(m == 0 && n == 0)
        return -1;

    if(m < 0) m = -m;
    if(n < 0) n = -n;

    int r;
    while(n) {
        r = m % n;
        m = n;
        n = r;
    }
    return m;
}

【讨论】:

  • 那个函数不是递归的......这证明你不需要递归方法,迭代就可以了。
  • 如果 n > m,则第一个循环交换 m 和 n(实际上:r = m%n == m;m = n;n = r)。进行更大的数字检查会将循环计数减少 1(除数减少 1),但这不是必需的。
猜你喜欢
  • 1970-01-01
  • 2020-12-05
  • 1970-01-01
  • 1970-01-01
  • 2012-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多