Python Tutorial Python Advanced Python References Python Libraries

Python math - gcd() Function



The Python math.gcd() function returns the greatest common divisor of the specified integer arguments. The GCD of two numbers is the largest number that divides both of them.

For example - GCD of 20 and 25 is 5, and GCD of 50 and 100 is 50.

In version 3.5 and later, the support for an arbitrary number of arguments is added. Formerly, only two arguments were supported.

Syntax

#Before version 3.5
math.gcd(a, b)

#From version 3.5
math.gcd(*args)

Parameters

a Required. Specify the first integer value.
b Required. Specify the second integer value.
*args Required. Specify the variable number of integer values separated by comma ,.

Return Value

Returns the GCD of the specified arguments.

Example:

In the example below, gcd() function returns the GCD of the specified arguments.

import math

print(math.gcd(35, 49))
print(math.gcd(225, 100))
print(math.gcd(12, 42))

The output of the above code will be:

7
25
6

Example:

The gcd() function can be used to calculate GCD of variable number of arguments. Please note that this feature is added in version 3.5.

import math

print(math.gcd(15, 30, 50))

The output of the above code will be:

5

❮ Python Math Module