Open In App

gcd() in Python

Last Updated : 14 Jun, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

gcd() function in Python is used to compute the Greatest Common Divisor (GCD) of two integers. It is available in the math module and returns the largest positive integer that divides both numbers without leaving a remainder. Example:

Python
import math
a = 60
b = 48

print(math.gcd(a, b))

Output
12

Explanation: The common divisors of 60 and 48 are [1, 2, 3, 4, 6, 12] and the greatest one is 12.

Syntax of math.gcd()

import math

math.gcd(x, y)

Parameters: x, y is Two non-negative integers (at least one of them must be non-zero).

Returns:

  • The greatest common divisor of x and y.
  • If either x or y is 0, the result is the absolute value of the non-zero number.

Examples of using math.gcd() function

Example 1: GCD of a number and 0

Python
import math

print(math.gcd(0, 25))

Output
25

Explanation: When one number is 0, the gcd() returns the absolute value of the other number.

Example 2: GCD of two co-prime numbers

Python
import math

print(math.gcd(17, 29))

Output
1

Explanation: 17 and 29 are co-prime (no common divisors except 1), so gcd() returns 1.

Example 3: GCD in a list of numbers using functools.reduce()

Python
import math
from functools import reduce

nums = [48, 64, 80]

# Find GCD of the list
res = reduce(math.gcd, nums)
print(res)

Output
16

Explanation: This finds the GCD of multiple numbers by applying math.gcd() cumulatively to the list elements.


Next Article
Article Tags :
Practice Tags :

Similar Reads