使用欧几里德算法的最大公约数?

时间:2015-10-19 20:13:33

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

所以我的代码出现问题。

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

任何帮助将不胜感激!

这是我到目前为止所拥有的

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

}

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

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

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