Learn and Learn

Learn And Learn - great place for tutorials, references and how-to

How to Find GCD or HCF in Python using gcd() Function

GCD stands for greatest common divisor. It is sometimes called highest common factor or divisor (HCF or HCD). We can define GCD or HCF as:

“GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of any two given numbers x and y is the largest positive number that divides both x and y numbers with zero remainders, where at least one of the numbers x and y is nonzero”.

For instance, the GCD of number 6 and 9 is 3.
For example:
The divisors of 6 are 1,2,3,6 and the divisors of 9 are 1,2,3,9.
If you notice carefully, 3 is the greatest factor that divides both 6 and 9 with zero remainders hence 3 is GCD or HCF of 6 and 9.

gcd() Function in Python

Python Standard math Library provides a built-in function gcd() to calculate GCD or HCF of any two or more given numbers.

 

Syntax of gcd() Function

The syntax of gcd() function in Python is:
math.gcd( x, y )

 

Parameters of gcd() function

x Any valid Python integer. This parameter is required.
y Any valid Python integer. This parameter is required.
Note: math.gcd() function uses at least two parameters to calculate GCD. That is why both parameters are required.

 

Python gcd() Function Compatibility

Python 2.x – Yes
Python 3.x – Yes

 

Return Value of gcd() in Python

Python gcd() function will return an absolute/positive integer value after calculating the GCD of given parameters x and y.

 

Common programming errors in gcd() function

If either x or y argument is zero, gcd() function returns TypeError
If data type of x or y argument is not a number, gcd() function returns TypeError.

 

Points to Ponder

If both x and y values are zero, gcd() returns zero
If none of the parameters is zero gcd() function returns a nonzero value.

 

Python gcd() Function Example


Output of Python gcd() function:
6
100
6
2
0

 

LearnAndLearn.com © 2018 - All rights reserved