分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击人工智能教程

/*
 * 求两个自然数的最大公约数 - C++ - by Chimomo
 *
 * Answer:辗转相除法
 */

#include <iostream>
#include <cassert>
#include <stack>
#include <math.h>

using namespace std;

int GreatestCommonDivisor(int a, int b) {
    int t;

    if (a < b) {
        // 交换两个数,使大数放在a的位置上。
        t = a;
        a = b;
        b = t;
    }

    while (b != 0) {
        // 利用辗转相除法,直到b为0为止。
        t = a % b;
        a = b;
        b = t;
    }

    return a;
}

int main() {
    cout << GreatestCommonDivisor(318, 87632) << endl;
    return 0;
}

// Output:
/*
2

*/

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐