I have a simple algorithm which calculate GCD for 2 integers. What I'm trying to do is to use result of this function to calculate GCD for more then 2 integers. For example GCD for 99 and 22 is 11. Then I want to use 11 as first integer and some number. The thing is I don't know how to use a first result to calculate another one. Especially if there are more then 3 integers because user decides for how many of them the GCD will be calculated. Here is my code (which work only for 2 integers):
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]))
If the idea is to use recursion for combining the results as well as in the algorithm itself then this will work:
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))
Another options include a loop (ok) or using functools.reduce
(not recommended as not readable enough).
Sounds like you are talking about recursion:
https://www.programiz.com/python-programming/recursion
Basically you just do another call to the same method, inside of that method:
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)))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.