Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python gcd for list

Tags:

I want to calculate gcd for a list of numbers. But I don't know what's wrong with my code.

A = [12, 24, 27, 30, 36]   def Greatest_Common_Divisor(A):     for c in A:         while int(c) > 0:             if int(c) > 12:                 c = int(c) % 12             else:                 return 12 % int(c)     print Greatest_Common_Divisor(A) 
like image 452
redmouse Avatar asked Mar 22 '15 12:03

redmouse


People also ask

How do you find the HCF of a list in Python?

num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) # printing the result for the users. print("The H.C.F. of", num1,"and", num2,"is", calculate_hcf(num1, num2))

Is there any GCD function in Python?

gcd() method returns the greatest common divisor of the two integers int1 and int2. GCD is the largest common divisor that divides the numbers without a remainder. GCD is also known as the highest common factor (HCF). Tip: gcd(0,0) returns 0.


2 Answers

here is the piece of code, that I used:

from fractions import gcd from functools import reduce def find_gcd(list):     x = reduce(gcd, list)     return x 
like image 112
Ayoub ABOUNAKIF Avatar answered Oct 05 '22 05:10

Ayoub ABOUNAKIF


As of python 3.9, python got built-in support for calculating gcd over a list of numbers.

import math A = [12, 24, 27, 30, 36] print(math.gcd(*A)) 

Output:

3 
like image 38
bigbounty Avatar answered Oct 05 '22 04:10

bigbounty