gcd() function Python

The Greatest Common Divisor (GCD) is the largest positive integer that divides both numbers without leaving a remainder. Python provides the gcd() function in the math module to calculate this efficiently.

Syntax

math.gcd(x, y)

Parameters:

  • x ? First integer
  • y ? Second integer

Return Value: Returns the greatest common divisor as an integer.

Example

Let's find the GCD of different pairs of numbers ?

import math

print("GCD of 75 and 30 is", math.gcd(75, 30))
print("GCD of 48 and 18 is", math.gcd(48, 18))
print("GCD of 17 and 13 is", math.gcd(17, 13))
GCD of 75 and 30 is 15
GCD of 48 and 18 is 6
GCD of 17 and 13 is 1

Special Cases

The gcd() function handles special cases like zero and negative numbers ?

import math

print("GCD of 0 and 12 is", math.gcd(0, 12))
print("GCD of 0 and 0 is", math.gcd(0, 0))
print("GCD of -24 and -18 is", math.gcd(-24, -18))
print("GCD of -15 and 25 is", math.gcd(-15, 25))
GCD of 0 and 12 is 12
GCD of 0 and 0 is 0
GCD of -24 and -18 is 6
GCD of -15 and 25 is 5

Finding GCD of Multiple Numbers

To find GCD of more than two numbers, use reduce() from the functools module ?

import math
from functools import reduce

numbers = [48, 18, 24, 12]
result = reduce(math.gcd, numbers)
print(f"GCD of {numbers} is {result}")

# Step by step calculation
print("Step by step:")
print(f"GCD(48, 18) = {math.gcd(48, 18)}")
print(f"GCD(6, 24) = {math.gcd(6, 24)}")
print(f"GCD(6, 12) = {math.gcd(6, 12)}")
GCD of [48, 18, 24, 12] is 6
Step by step:
GCD(48, 18) = 6
GCD(6, 24) = 6
GCD(6, 12) = 6

Conclusion

The math.gcd() function efficiently calculates the greatest common divisor of two integers. For multiple numbers, combine it with reduce() to find the GCD of all values.

Updated on: 2026-03-15T19:09:30+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements