# How to calculate greatest common divisor in python

To find the greatest common divisor (G.C.D.) of two integers on Python, use the gcd() function of the math module

**math.gcd(a,b)**

Parameters a and b are two integer numeric values.

The greatest common divisor (gcd) function finds the highest integer that can divide both a and b values.

**Note**. To use the gcd () function you need to import it into Python using the import or from import command.

__Alternative method__

Alternatively, you can create a gcd() function in the script without importing the math module

def gcd(x,y):

while(y):

x,y=y,x%y

return x

## Examples

__Example 1__

This script calculates the greatest common divisor (G.C.D.) of the numbers 14 and 6 via the function **gcd()**.

import math

math.gcd(14,6)

The function returns in output

2

The integer number 2 is the greatest common divisor of 14 and 6.

__Example 2__

This script calculates the greatest common divisor of 12 and 6.

import math

math.gcd(12,6)

The gcd() function returns as output

6

The integer 6 is the highest divisor value that can divide both 12 and 6.

__Example 3__

This script calculates the M.C.D. of 14 and 0.

import math

math.gcd(14,0)

The output result is the following

14

If one of the two numbers is a zero, the greatest common factor is the other number, because zero is divisible by any number.

**Report an error or share a suggestion to enhance this page**