(Compute GCD) Write a function that returns the greatest common divisor (GCD) of integers in a list. Use the following function header:
def gcd(numbers):
Write a test program that prompts the user to enter five numbers, invokes the function to find the GCD of these numbers, and displays the GCD.
Compute GCD Program code:
# Function to calculate the greatest common divisor (GCD)
def gcd(numbers):
# Find the GCD of the first two numbers
result = numbers[0]
for i in range(1, len(numbers)):
result = computeGCD(result, numbers[i])
return result
# Helper function to calculate the GCD of two numbers using Euclidean algorithm
def computeGCD(a, b):
while b:
a, b = b, a % b
return a
# Test program
def main():
# Prompt the user to enter five numbers separated by spaces
num = input("Enter five numbers: ")
# Convert the input string to a list of numbers
numbers = [int(num) for num in num.split()]
# Calculate the GCD of the numbers
result = gcd(numbers)
# Display the GCD
print("The greatest common divisor (GCD) is:", result)
# Call the test program
main()
Executed Output:
Enter five numbers: 5 15 2 10 8
The greatest common divisor (GCD) is: 1