原文: https://www.programiz.com/cpp-programming/examples/hcf-recursion
要理解此示例,您应该了解以下 C++ 编程主题:
该程序从用户获取两个正整数,并使用递归计算 GCD。
访问此页面以了解如何使用循环来计算 GCD。
#include <iostream>
using namespace std;
int hcf(int n1, int n2);
int main()
{
int n1, n2;
cout << "Enter two positive integers: ";
cin >> n1 >> n2;
cout << "HCF of " << n1 << " & " << n2 << " is: " << hcf(n1, n2);
return 0;
}
int hcf(int n1, int n2)
{
if (n2 != 0)
return hcf(n2, n1 % n2);
else
return n1;
} 输出
Enter two positive integers: 366 60
HCF of 366 and 60 is: 6