gcd(x,y) = y; 如果y除以x而沒有餘數
gcd(x,y) = gcd(y, x/y的餘數);否則
// This program demonstrates a recursive function to // calculate the greatest common divisor (gcd) of two numbers. #include <iostream> using namespace std; // Function prototype int gcd(int, int); int main() { int num1, num2; cout << "Enter two integers: "; cin >> num1 >> num2; cout << "The greatest common divisor of " << num1; cout << " and " << num2 << " is "; cout << gcd(num1, num2) << endl; return 0; } int gcd(int x, int y) { if (x % y == 0) //base case return y; else return gcd{y, x % y); }程式輸出結果:
Enter two integers: 49 28
The greatest common divisor of 49 and 28 is 7