gcd(x,y) = y; 如果y除以x而没有余数
gcd(x,y) = gcd(y,x/y的余数);否则
下面的程序显示了递归的 C++ 实现:
// 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。