我有一个简单的算法,可以计算2个整数的GCD。 我要做的是使用此函数的结果计算超过2个整数的GCD。例如99和22的GCD是11.然后我想使用11作为第一个整数和一些数字。问题是我不知道如何使用第一个结果来计算另一个结果。特别是如果有超过3个整数,因为用户决定将计算多少个整数。 这是我的代码(仅适用于2个整数):
required_inputs = int(input("For how many numbers would you like to find their GCD?: "))
received_inputs = []
for num in range(0, required_inputs):
values = int(input())
received_inputs.append(values)
if len(received_inputs) == 0:
values = int(input())
received_inputs.append(values)
def GCD(a, b):
if b == 0:
return a
else:
return GCD(b, a % b)
print(GCD(received_inputs[0], received_inputs[1]))
答案 0 :(得分:0)
如果想要使用递归来组合结果以及算法本身,那么这将起作用:
def GCD(*numbers):
a, b = numbers[:2]
if len(numbers) == 2:
if b == 0:
return a
else:
return GCD(b, a % b)
else:
return GCD(GCD(a, b), *numbers[2:])
print(GCD(*received_inputs))
另一个选项包括循环(ok)或使用functools.reduce
(不建议不够可读)。
答案 1 :(得分:-1)
听起来你在谈论递归:
https://www.programiz.com/python-programming/recursion
基本上你只是在该方法中对同一个方法进行另一次调用:
def calc_factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return x * calc_factorial(x - 1)
num = 4
print("The factorial of {} is {}".format(num, calc_factorial(num)))