比较好用的有这么几种:
1、辗转相除法
C语言:
#include <stdio.h> int main() { int a, b, r;//两数a,b scanf("%d%d", &a, &b); r = a % b; while (r != 0) { a = b; b = r; r = a % b; } printf("%d", b);//b即为公因数 }
C++:
#include <iostream> using namespace std; int main() { int a, b, r;//两数a,b cin >> a >> b; r = a % b; while (r != 0) { a = b; b = r; r = a % b; } cout << b; //b即为公因数 }
2.辗转相减法
原理:
m不等于n,循环以下条件:
1.若m>n,使m=m-n;
2.若m
最后m与n相同,函数返回m或n即可
C语言:
#include <stdio.h> int gongyueshu(int m, int n) {//求公因数函数 while (m != n) { if (m > n) m = m - n; else n = n - m; } return n; } int main() { int x, y; scanf("%d%d", &x, &y); printf("%d", gongyueshu(x, y)); }
C++:
#include <iostream> using namespace std; int gongyueshu(int m, int n) {//求公因数函数 while (m != n) { if (m > n) m = m - n; else n = n - m; } return n; } int main() { int x, y; cin >> x >> y; cout << gongyueshu(x, y); }
3.C++中的特殊函数__gcd()
//__gcd()函数(注意有两个下划线_) #include <iostream> #include <algorithm>//要用函数所需要的头文件 using namespace std; int main() { int x = 11, y = 33; cout << __gcd(x, y); }