SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Y Daniel Lang
Chapter:
0.lists
Exercise:
Programming Excercises
Question:12 | ISBN:978013274719 | Edition: 6

Question

(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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.