1. Programming questions:
The greatest common divisor (GCD) is the largest of the common divisors of two or more integers. For example, the greatest common divisor of 12 and 18 is 6.
Write a program to find the greatest common divisor of a list of numbers.
Define the function find gcd of numbers() which takes a parameter numbers list.
Inside the function, the greatest common divisor of the numbers in the list is calculated and returned.
First, refine the function gcd(), which is used to calculate the greatest common divisor of two numbers. Use this gcd() function in find gcd of numbers() to calculate the greatest common divisor of the list of numbers. Sample input.
Sample output. Explanation: 1 is the greatest positive integer, i.e., the greatest common divisor, that is divisible by all given numbers and leaves no remainders.
2. Implementation:
Editable ** as follows:
#!/usr/bin/python3.9
# -*coding: utf-8 -*
## copyright (c) 2024 , inc. all rights reserved
## @time : 2024/2/16 18:12
# @author : fangel
# @filename : 110.The greatest common divisor in the list. py
# @software : pycharm
Defines the function for finding the greatest common divisor.
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
def find_gcd_of_numbers(numbers_list):
i = 0 assigns the first element in the list to resgcd
resgcd = numbers_list[0]
Loop through the list, and continue to find the greatest common divisor of the first two numbers and the next number.
while i < len(numbers_list) -1:
resgcd = gcd(resgcd, numbers_list[i + 1])
i += 1
return resgcd
Takes integer input and converts to a list.
numbers_list = list(map(int, input().split())
Call the function.
print(find_gcd_of_numbers(numbers_list))
3. Analysis:
The greatest common divisor of a list of numbers can be calculated by calculating the greatest common divisor of the current result with the next number in the list one by one.
4. Running result: February**Dynamic incentive plan Input:
Output: