说明:
最初跟鹏哥学习最大公约数的算法是辗转相除, 确实印象很深刻, 那种辗转赋值的思想在好多题目中都有运用, 但随着进一步学习, 我也参考了其他几种方便快捷的最大公约数求法, 在这里做一个总结
- 1.
- int gcd(int a,int b) /// 基础 辗转
- {
- int r;
- while(b>0)
- {
- r=a%b;
- a=b;
- b=r;
- }
- return a;
- }
- 2.
- int gcd(int a,int b)/// 位运算
- {
- while(b^=a^=b^=a%=b);
- return a;
- }
- 3.
- int gcd(int a,int b)/// 递归
- {
- return (b>0)?gcd(b,a%b):a;
- }
- 4.
- #include<algorithm>/// 直接使用 c++ 的内置函数
- using namespace std;
- __gcd(int a,int b)
来源: http://www.bubuko.com/infodetail-2543027.html