python用递归方式实现最大公约数_C++最大公约数(递归)详解

使用递归可以计算两个数字的最大公约数。根据欧几里得算法,两个正整数 x 和 y 的最大公约数的计算方法如下:

gcd(x,y) = y; 如果y除以x而没有余数

gcd(x,y) = gcd(y, x/y的余数);否则

这个定义指出,如果 x/y 没有余数,则 x 和 y 的最大公约数是 y;否则,答案就是 y 和 x/y 的余数的最大公约数。

下面的程序显示了递归的 C++ 实现:

// This program demonstrates a recursive function to

// calculate the greatest common divisor (gcd) of two numbers.

#include

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值