Using Euclid Algorithm to find GCF(GCD)

淺唱寂寞╮ 提交于 2019-12-08 08:19:26

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