1 #include <iostream> 2 using namespace std; 3 4 int main() 5 { 6 int a, b, c; 7 cin >> a >> b; 8 while(b != 0) { 9 c = a % b; 10 a = b; 11 b = c; 12 if (b == 1) { 13 cout << "互质" << endl; 14 break; 15 } 16 } 17 if (b == 0) cout << "最大公约数为 "<< a << endl; 18 }
原理基于辗转相除法;
还可以是:(递归)
1 int gcd (int a, int b) {
2 return b == 0 ? a : gcd(b, a % b);
3 }