Python math.gcd()

Anonymous contributor's avatar
Anonymous contributor
Published Aug 21, 2024
Contribute to Docs

The math.gcd() function in Python returns the Greatest Common Divisor (GCD) of two or more integers. The GCD is the largest positive integer that divides all of the given numbers without leaving a remainder.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours

Syntax

math.gcd(*integers)
  • *integers: This represents the integers for which to compute the GCD.

Example

The example below uses the math.gcd() function to return the greatest common divisor of the specified integers:

import math
# GCD of two integers.
print(math.gcd(54, 24))
# GCD of more than two integers.
print(math.gcd(54, 108, 216))
# GCD of zero and non-zero integers.
print(math.gcd(54, 0))

The output of the example code above is:

6
54
54

Note: If math.gcd() function is called with no arguments or if all arguments are zero (0), it will return zero (0).

Codebyte Example

Run the following example that uses the math.gcd() function to understand how it works:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn Python on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours