Thursday, January 29, 2026
HomeLanguagesPython | math.gcd() function

Python | math.gcd() function

In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.gcd() function compute the greatest common divisor of 2 numbers mentioned in its arguments.

Syntax: math.gcd(x, y) Parameter: x : Non-negative integer whose gcd has to be computed. y : Non-negative integer whose gcd has to be computed. Returns: An absolute/positive integer value after calculating the GCD of given parameters x and y. Exceptions : When Both x and y are 0, function returns 0, If any number is a character, Type error is raised.

Time Complexity: O(1)

Auxiliary Space: O(1)

Code #1: 

Python3




# Python code to demonstrate the working of gcd()
     
# importing "math" for mathematical operations
import math
     
# prints 12
print ("The gcd of 60 and 48 is : ", end ="")
print (math.gcd(60, 48))


Output:

The gcd of 60 and 48 is : 12

  Code #2: 

Python3




# Python code to demonstrate the working of gcd()
 
# importing "math" for mathematical operations
import math
 
# prints gcd of x, y
print ("math.gcd(44, 12) : ", math.gcd(44, 12))
print ("math.gcd(69, 23) : ", math.gcd(65, 45))


Output:

math.gcd(44, 12) :  4
math.gcd(69, 23) :  5

Code #3: Explaining Exception. 

Python3




# Python code to demonstrate gcd()
# method exceptions
import math
     
# prints 0
print ("The gcd of 0 and 0 is : ", end ="")
print (math.gcd(0, 0))
     
# Produces error
print ("\nThe gcd of a and 13 is : ", end ="")
print (math.gcd('a', 13))


Output: 

The gcd of 0 and 0 is : 0

The gcd of a and 13 is : 
TypeError: 'str' object cannot be interpreted as an integer
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32476 POSTS0 COMMENTS
Milvus
122 POSTS0 COMMENTS
Nango Kala
6848 POSTS0 COMMENTS
Nicole Veronica
11978 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12065 POSTS0 COMMENTS
Shaida Kate Naidoo
6986 POSTS0 COMMENTS
Ted Musemwa
7221 POSTS0 COMMENTS
Thapelo Manthata
6934 POSTS0 COMMENTS
Umr Jansen
6916 POSTS0 COMMENTS