import math
math.gcd(2, 6, 12) # 2
math.gcd
Changed in version 3.9: Added support for an arbitrary number of arguments. Formerly, only two arguments were supported.
До версии 3.9, но выше 3.5 можно скомбинировать так:
math.gcd(3, math.gcd(6, 12)) # 3
Пример:
from math import gcd
from functools import reduce
reduce(gcd, [3, 12, 6, 18]) # 3
Для версии ниже 3.5:
from functools import reduce
def gcd(a, b):
return gcd(b, a % b) if b else a
reduce(gcd, [3, 6, 12]) # 3
Как найти НОК или НОД в python 3.9 в списке из n кол-ва чисел? (Ввод чисел пользователем)
(н: math.gcd([1 , 2 , 3])
задан 26 окт 2021 в 16:22
4
список из нескольких чисел можно получить следующим образом:
data = list(map(int, input().split()))
весь код таким образом будет выглядеть так:
import math
data = list(map(int, input().split()))
gcd = math.gcd(*data)
lcm = math.lcm(*data)
print(gcd, lcm)
ответ дан 26 окт 2021 в 16:42
ZhiharZhihar
36.9k4 золотых знака25 серебряных знаков67 бронзовых знаков
1
print ('a = ', end = '')
a = int (input ())
print ('b = ', end = '')
b = int (input ())
p = a * b
while a != 0 and b != 0:
if a > b:
a = a % b
else:
b = b % a
nod = a + b
nok = p // nod
print ('GCD:', nok)
print ('LDM:', nod)
ответ дан 26 окт 2021 в 16:29
2
2 / 2 / 0 Регистрация: 25.03.2018 Сообщений: 91 |
|
1 |
|
Наибольший общий делитель для списка натуральных чисел26.03.2018, 20:25. Показов 33682. Ответов 11
В модуле math есть функция math.gcd(a, b), возвращающая наибольший общий делитель (НОД) двух чисел. При помощи functools.reduce вычислите и напечатайте наибольший общий делитель для списка натуральных чисел, поступающих в стандартный поток ввода. Формат ввода Формат вывода
0 |
Просто Лис 5092 / 3259 / 1008 Регистрация: 17.05.2012 Сообщений: 9,551 Записей в блоге: 9 |
|
27.03.2018, 06:33 |
2 |
И? В чём сложности?
0 |
2 / 2 / 0 Регистрация: 25.03.2018 Сообщений: 91 |
|
27.03.2018, 16:06 [ТС] |
3 |
Рыжий Лис, не понял как это сделать
0 |
Просто Лис 5092 / 3259 / 1008 Регистрация: 17.05.2012 Сообщений: 9,551 Записей в блоге: 9 |
|
27.03.2018, 16:31 |
4 |
functools.reduce не знаете как воспользоваться?
0 |
2 / 2 / 0 Регистрация: 25.03.2018 Сообщений: 91 |
|
27.03.2018, 16:35 [ТС] |
5 |
Рыжий Лис, знал бы — не написал бы сюда
0 |
Рыжий Лис Просто Лис 5092 / 3259 / 1008 Регистрация: 17.05.2012 Сообщений: 9,551 Записей в блоге: 9 |
||||
27.03.2018, 16:44 |
6 |
|||
Аха-ха-ха:
0 |
2 / 2 / 0 Регистрация: 25.03.2018 Сообщений: 91 |
|
28.03.2018, 22:23 [ТС] |
7 |
Рыжий Лис, Answers do not match: out = 6, corr = 1
0 |
IRIP 513 / 145 / 27 Регистрация: 18.04.2015 Сообщений: 1,872 Записей в блоге: 15 |
||||
09.07.2018, 15:57 |
8 |
|||
Pavlin235, вот вроде решение
Добавлено через 6 минут
0 |
Garry Galler 5407 / 3831 / 1214 Регистрация: 28.10.2013 Сообщений: 9,554 Записей в блоге: 1 |
||||
09.07.2018, 16:32 |
9 |
|||
Как можно еще больше сократить это решение?
Но ТС нужна была не кастомная функция НОД, а функциональный подход с использованием reduce для списка.
0 |
IRIP 513 / 145 / 27 Регистрация: 18.04.2015 Сообщений: 1,872 Записей в блоге: 15 |
||||
09.07.2018, 16:50 |
10 |
|||
Но ТС нужна была не кастомная функция НОД, а функциональный подход с использованием reduce для списка вроде мы с ним по одной программе занимаемся… конкретно вот этот код как можно сократить, чтобы он сохранял свою работоспособность?
заменить везде число1 = число1 % число2 на число1 %= число2
0 |
Рюмка_на_столе 15 / 15 / 0 Регистрация: 05.01.2020 Сообщений: 8 |
||||
16.03.2020, 19:37 |
11 |
|||
3 |
57 / 54 / 3 Регистрация: 02.11.2019 Сообщений: 228 |
|
10.04.2020, 14:46 |
12 |
Рюмка_на_столе, супер! Просто жжешь!
0 |
Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
The GCD of three or more numbers equals the product of the prime factors common to all the numbers, but it can also be calculated by repeatedly taking the GCDs of pairs of numbers.
gcd(a, b, c) = gcd(a, gcd(b, c)) = gcd(gcd(a, b), c) = gcd(gcd(a, c), b)
Python
def
find_gcd(x, y):
while
(y):
x, y
=
y, x
%
y
return
x
l
=
[
2
,
4
,
6
,
8
,
16
]
num1
=
l[
0
]
num2
=
l[
1
]
gcd
=
find_gcd(num1,num2)
for
i
in
range
(
2
,
len
(l)):
gcd
=
find_gcd(gcd,l[i])
print
(gcd)
Output:
2
Time complexity : O(n + log(min(a, b))), as the function goes through the list of numbers and finds the GCD for each pair of numbers using the Euclidean algorithm.
Auxiliary Space: O(log x), as the function only uses a few variables to store the GCD and the numbers being compared.
Please refer complete article on GCD of more than two (or array) numbers for more details!
Last Updated :
09 Feb, 2023
Like Article
Save Article
So I’m writing a program in Python to get the GCD of any amount of numbers.
def GCD(numbers):
if numbers[-1] == 0:
return numbers[0]
# i'm stuck here, this is wrong
for i in range(len(numbers)-1):
print GCD([numbers[i+1], numbers[i] % numbers[i+1]])
print GCD(30, 40, 36)
The function takes a list of numbers.
This should print 2. However, I don’t understand how to use the the algorithm recursively so it can handle multiple numbers. Can someone explain?
updated, still not working:
def GCD(numbers):
if numbers[-1] == 0:
return numbers[0]
gcd = 0
for i in range(len(numbers)):
gcd = GCD([numbers[i+1], numbers[i] % numbers[i+1]])
gcdtemp = GCD([gcd, numbers[i+2]])
gcd = gcdtemp
return gcd
Ok, solved it
def GCD(a, b):
if b == 0:
return a
else:
return GCD(b, a % b)
and then use reduce, like
reduce(GCD, (30, 40, 36))
asked May 18, 2013 at 19:19
TetramputechtureTetramputechture
2,9112 gold badges32 silver badges47 bronze badges
3
Since GCD is associative, GCD(a,b,c,d)
is the same as GCD(GCD(GCD(a,b),c),d)
. In this case, Python’s reduce
function would be a good candidate for reducing the cases for which len(numbers) > 2
to a simple 2-number comparison. The code would look something like this:
if len(numbers) > 2:
return reduce(lambda x,y: GCD([x,y]), numbers)
Reduce applies the given function to each element in the list, so that something like
gcd = reduce(lambda x,y:GCD([x,y]),[a,b,c,d])
is the same as doing
gcd = GCD(a,b)
gcd = GCD(gcd,c)
gcd = GCD(gcd,d)
Now the only thing left is to code for when len(numbers) <= 2
. Passing only two arguments to GCD
in reduce
ensures that your function recurses at most once (since len(numbers) > 2
only in the original call), which has the additional benefit of never overflowing the stack.
answered May 18, 2013 at 19:53
alexkonradialexkonradi
7505 silver badges5 bronze badges
You can use reduce
:
>>> from fractions import gcd
>>> reduce(gcd,(30,40,60))
10
which is equivalent to;
>>> lis = (30,40,60,70)
>>> res = gcd(*lis[:2]) #get the gcd of first two numbers
>>> for x in lis[2:]: #now iterate over the list starting from the 3rd element
... res = gcd(res,x)
>>> res
10
help on reduce
:
>>> reduce?
Type: builtin_function_or_method
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
answered May 18, 2013 at 19:27
Ashwini ChaudharyAshwini Chaudhary
243k58 gold badges460 silver badges503 bronze badges
2
Python 3.9 introduced multiple arguments version of math.gcd
, so you can use:
import math
math.gcd(30, 40, 36)
3.5 <= Python <= 3.8.x:
import functools
import math
functools.reduce(math.gcd, (30, 40, 36))
3 <= Python < 3.5:
import fractions
import functools
functools.reduce(fractions.gcd, (30, 40, 36))
answered May 13, 2020 at 16:08
Yam MesickaYam Mesicka
6,2157 gold badges45 silver badges64 bronze badges
A solution to finding out the LCM of more than two numbers in PYTHON is as follow:
#finding LCM (Least Common Multiple) of a series of numbers
def GCD(a, b):
#Gives greatest common divisor using Euclid's Algorithm.
while b:
a, b = b, a % b
return a
def LCM(a, b):
#gives lowest common multiple of two numbers
return a * b // GCD(a, b)
def LCMM(*args):
#gives LCM of a list of numbers passed as argument
return reduce(LCM, args)
Here I’ve added +1 in the last argument of range() function because the function itself starts from zero (0) to n-1. Click the hyperlink to know more about range() function :
print ("LCM of numbers (1 to 5) : " + str(LCMM(*range(1, 5+1))))
print ("LCM of numbers (1 to 10) : " + str(LCMM(*range(1, 10+1))))
print (reduce(LCMM,(1,2,3,4,5)))
those who are new to python can read more about reduce() function by the given link.
answered May 28, 2015 at 6:22
MD SARFARAZMD SARFARAZ
1172 silver badges17 bronze badges
The GCD operator is commutative and associative. This means that
gcd(a,b,c) = gcd(gcd(a,b),c) = gcd(a,gcd(b,c))
So once you know how to do it for 2 numbers, you can do it for any number
To do it for two numbers, you simply need to implement Euclid’s formula, which is simply:
// Ensure a >= b >= 1, flip a and b if necessary
while b > 0
t = a % b
a = b
b = t
end
return a
Define that function as, say euclid(a,b)
. Then, you can define gcd(nums)
as:
if (len(nums) == 1)
return nums[1]
else
return euclid(nums[1], gcd(nums[:2]))
This uses the associative property of gcd() to compute the answer
answered May 18, 2013 at 19:23
torquestomptorquestomp
3,30418 silver badges26 bronze badges
3
Try calling the GCD()
as follows,
i = 0
temp = numbers[i]
for i in range(len(numbers)-1):
temp = GCD(numbers[i+1], temp)
answered May 18, 2013 at 19:28
DeepuDeepu
7,5844 gold badges25 silver badges47 bronze badges
My way of solving it in Python. Hope it helps.
def find_gcd(arr):
if len(arr) <= 1:
return arr
else:
for i in range(len(arr)-1):
a = arr[i]
b = arr[i+1]
while b:
a, b = b, a%b
arr[i+1] = a
return a
def main(array):
print(find_gcd(array))
main(array=[8, 18, 22, 24]) # 2
main(array=[8, 24]) # 8
main(array=[5]) # [5]
main(array=[]) # []
Some dynamics how I understand it:
ex.[8, 18] -> [18, 8] -> [8, 2] -> [2, 0]
18 = 8x + 2 = (2y)x + 2 = 2z where z = xy + 1
ex.[18, 22] -> [22, 18] -> [18, 4] -> [4, 2] -> [2, 0]
22 = 18w + 4 = (4x+2)w + 4 = ((2y)x + 2)w + 2 = 2z
answered Jul 24, 2018 at 2:06
Zoe LZoe L
1,10914 silver badges21 bronze badges
As of python 3.9 beta 4, it has got built-in support for finding gcd over a list of numbers.
Python 3.9.0b4 (v3.9.0b4:69dec9c8d2, Jul 2 2020, 18:41:53)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> A = [30, 40, 36]
>>> print(math.gcd(*A))
2
answered Aug 5, 2020 at 2:24
bigbountybigbounty
16.2k5 gold badges36 silver badges63 bronze badges
One of the issues is that many of the calculations only work with numbers greater than 1. I modified the solution found here so that it accepts numbers smaller than 1. Basically, we can re scale the array using the minimum value and then use that to calculate the GCD of numbers smaller than 1.
# GCD of more than two (or array) numbers - alows folating point numbers
# Function implements the Euclidian algorithm to find H.C.F. of two number
def find_gcd(x, y):
while(y):
x, y = y, x % y
return x
# Driver Code
l_org = [60e-6, 20e-6, 30e-6]
min_val = min(l_org)
l = [item/min_val for item in l_org]
num1 = l[0]
num2 = l[1]
gcd = find_gcd(num1, num2)
for i in range(2, len(l)):
gcd = find_gcd(gcd, l[i])
gcd = gcd * min_val
print(gcd)
answered Aug 10, 2020 at 19:04
Nikhil GuptaNikhil Gupta
1,39612 silver badges15 bronze badges
HERE IS A SIMPLE METHOD TO FIND GCD OF 2 NUMBERS
a = int(input("Enter the value of first number:"))
b = int(input("Enter the value of second number:"))
c,d = a,b
while a!=0:
b,a=a,b%a
print("GCD of ",c,"and",d,"is",b)
answered Oct 24, 2020 at 5:35
As You said you need a program who would take any amount of numbers
and print those numbers’ HCF.
In this code you give numbers separated with space and click enter to get GCD
num =list(map(int,input().split())) #TAKES INPUT
def print_factors(x): #MAKES LIST OF LISTS OF COMMON FACTROS OF INPUT
list = [ i for i in range(1, x + 1) if x % i == 0 ]
return list
p = [print_factors(numbers) for numbers in num]
result = set(p[0])
for s in p[1:]: #MAKES THE SET OF COMMON VALUES IN LIST OF LISTS
result.intersection_update(s)
for values in result:
values = values*values #MULTIPLY ALL COMMON FACTORS TO FIND GCD
values = values//(list(result)[-1])
print('HCF',values)
Hope it helped
answered Nov 11, 2022 at 14:03