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:
Basic Function Usage
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
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
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.