可以使用輾轉(zhuǎn)相除法(歐幾里德算法)來求解兩個數(shù)的最大公約數(shù),C++代碼示例如下:
#include <iostream>
using namespace std;
int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
int main() {
int num1, num2;
cout << "請輸入兩個數(shù):" << endl;
cin >> num1 >> num2;
int result = gcd(num1, num2);
cout << "最大公約數(shù)是:" << result << endl;
return 0;
}
在上面的代碼中,定義了一個gcd()
函數(shù)來實現(xiàn)最大公約數(shù)的計算,然后在main()
函數(shù)中接收用戶輸入的兩個數(shù),調(diào)用gcd()
函數(shù)求解最大公約數(shù)并輸出結(jié)果。