Python math.gcd() Method

This tutorial will guide you on the function syntax, parameters, return values and provide several practical examples to illustrate its functionality.

Python math.gcd() Method

Python's math.gcd() method is a powerful tool that returns the greatest common divisor of two numbers. In simple terms, it allows us to find the the largest integer that can divide both numbers without leaving a remainder.

Import the Python Math Module

Before we can use the math.gcd() function, we need to import the math module:

import math

Basic Function Usage

The math.gcd() function takes two arguments and returns the greatest common divisor of the two numbers.

If either of the numbers is zero, it returns the absolute value of the non-zero number.

The following example demonstrates the basic usage of the gcd() function.

import math
print(math.gcd(60, 48))



Example with Zero

What happens if one of the parameters is set to 0?

import math
print(math.gcd(0, 8))



In this case, the function returns the first non-zero number. This is because the greatest common divisor of 0 and any number is the absolute value of that number.

Working with Negative Numbers

The math.gcd() function also works with negative numbers. It will always return a non-negative result.

import math
print(math.gcd(-60, 48))



Similarly, the output is 12, because the gcd of negative values is similar to that of their positive equivalents.


This tutorial has introduced you to Python's math.gcd() function, showing you how to use it to find the greatest common divisor of two numbers. It's a useful function in many different mathematical and practical contexts, and understanding how to use it effectively will be a valuable addition to your Python toolset.

Table of Contents
Great! Next, complete checkout for full access to GeekBits.
Welcome back! You've successfully signed in.
You've successfully subscribed to GeekBits.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.