Using Euclid Algorithm to find GCF(GCD)

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-08 03:41:57

问题


I am trying to write a function to find the gcd of 2 numbers, using Euclid's Algorithm which I found here.

From the larger number, subtract the smaller number as many times as you can until you have a number that is smaller than the small number. (or without getting a negative answer) Now, using the original small number and the result, a smaller number, repeat the process. Repeat this until the last result is zero, and the GCF is the next-to-last small number result. Also see our Euclid's Algorithm Calculator.
Example: Find the GCF (18, 27)
27 - 18 = 9
18 - 9 = 9
9 - 9 = 0
So, the greatest common factor of 18 and 27 is 9, the smallest result we had before we reached 0.

Following these instructions I wrote a function:

int hcf(int a, int b)
{
    int small = (a < b)? a : b;
    int big = (a > b)? a : b;
    int res;
    int gcf;

    cout << "small = " << small << "\n";
    cout << "big = " << big << "\n";

    while ((res = big - small) > small && res > 0) {
            cout << "res = " << res << "\n"; 
    }
    while ((gcf = small - res) > 0) {
        cout << "gcf = " << gcf << "\n";
    }


    return gcf;
}

However, the second loop seems to be infinite. Can anyone explain why?

I know the website actually shows the code(PHP), but I'm trying to write this code using only the instructions they give.


回答1:


Of course this loop is infinite:

while ((gcf = small - res) > 0) {
    cout << "gcf = " << gcf << "\n";
}

small and res don't change in the loop, so gcf doesn't either. That loop is equivalent to:

gcf = small - res;
while (gcf > 0) {
    cout << "gcf = " << gcf << "\n";
}

which is probably more clear.

I would port that algorithm to code as follows:

int gcd(int a, int b) {
    while (a != b) {
        if (a > b) {
            a -= b;
        }
        else {
            b -= a;
        }
    }
    return a;
}

Although typically gcd is implemented using mod, since it's much faster:

int gcd(int a, int b) {
    return (b == 0) ? a : gcd(b, a % b);
}


来源:https://stackoverflow.com/questions/28267611/using-euclid-algorithm-to-find-gcfgcd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!