算法 - 求两个自然数的最大公约数(C++)
分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.net/** 求两个自然数的最大公约数 - C++ - by Chimomo** Answer:辗转相除法*/#include <iostream>#include <cassert>#include &
·
分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击人工智能教程
/*
* 求两个自然数的最大公约数 - 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
*/
更多推荐
已为社区贡献8条内容
所有评论(0)