Python 求最小公倍数和最大公约数的递归写法


# 最小公倍数
def lcm(a, b, c=1):
        if a * c % b != 0:
                return lcm(a, b, c+1)
        else:
                return a*c

test_cases = [(4, 8), (35, 42), (5, 7), (20, 10)]
for case in test_cases:
    print('lcm of {} & {} is {}'.format(*case, lcm(*case)))

def lcm(a, b):
    for i in range(2, min(a,b)+1):
        if a % i == 0 and b % i == 0:
            return i * lcm(a//i, b//i)
    else:
        return a*b


    
test_cases = [(4, 8), (5, 7), (24, 16), (35, 42)]
for case in test_cases:
    print('lcm of {} & {} is {}'.format(*case, lcm(*case)))

# 最大公约数
def gcd(a, b):
	if a == b:
		return a
	elif a-b > b:
		return gcd(a-b, b)
	else:
		return gcd(b, a-b)
	    
test_cases = [(35, 14), (88, 66), (5, 4), (20, 10)]
for case in test_cases:
    print('GCD of {} & {} is {}'.format(*case, gcd(*case)))

lcm of 4 & 8 is 8
lcm of 35 & 42 is 210
lcm of 5 & 7 is 35
lcm of 20 & 10 is 20
GCD of 35 & 14 is 7
GCD of 88 & 66 is 22
GCD of 5 & 4 is 1
GCD of 20 & 10 is 10

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值