With Python, we can calculate the greatest common divisor of two numbers with the math gcd() function.

import math

print(math.gcd(10,25))

#Output:
5

The Python math module has many powerful functions which make performing certain calculations in Python very easy.

One such calculation which is very easy to perform in Python is finding the greatest common divisor (GCD) of two numbers.

We can find the GCD of two numbers easily with the Python math module gcd() function. The math.gcd() function takes two integers and returns the GCD of those two integers.

Below are some examples of how to use math.gcd() in Python to find the GCD of two numbers.

import math

print(math.gcd(10,25))
print(math.gcd(90,33))
print(math.gcd(85,1003))
print(math.gcd(74,46))

#Output:
5
3
17
2

How to Get the Greatest Common Divisor of a List in Python with gcd() Function

To find the GCD of a list of numbers in Python, we need to use the fact that the GCD of a list of numbers will be the max of all pairwise GCDs in a list of numbers.

To get the GCD of a list of integers with Python, we loop over all integers in our list and find the GCD at each iteration in the loop.

Below is an example function in Python which will calculate the GCD of a list of integers using a loop and the math gcd() function.

import math

def gcd_of_list(ints):
    gcd = math.gcd(ints[0],ints[1])
    for i in range(2,len(ints)):
        gcd = math.gcd(gcd,ints[i])
    return gcd

print(gcd_of_list([11,33,1100]))
print(gcd_of_list([582,404,1028]))
print(gcd_of_list([990,675,320]))

#Output:
11
2
5

Hopefully this article has been useful for you to understand how to use the gcd() math function in Python to find the greatest common divisors of a list of numbers.

Categorized in:

Python,

Last Update: February 26, 2024