Python gcd

The Python math gcd function returns the greatest common divisor of two given arguments. In this section, we discuss how to use the gcd function with an example.

The syntax of the gcd Function in Python Programming Language is

math.gcd(x, y);

Please specify the X and Y values here. The gcd Function uses these X and Y arguments to find the greatest common divisor.

  • If both the X and Y arguments are Zero, the gcd function returns the output as Zero.
  • If either the X or Y is Zero, it returns the Non-zero value as the greatest common divisor.
  • Next, if either the X or Y is a Decimal, or If the X value or Y value argument is not a number, it returns TypeError.

Python gcd Function Example

The Python gcd function in the math module returns the greatest common divisor of two given arguments. In this example, We are going to find the greatest common divisor of different data types and display the output.

import math

Tup = (10, 20, 12, -40 , 50) # Tuple Declaration
Lis = [-98, 32, -39, -42 , 15] # List Declaration

print('Calculating GCD of Positive Number = %d' %math.gcd(2, 3))
print('Calculating GCD of Negative Number = %d' %math.gcd(-2, 3))

print('Calculating GCD of Zero = %d' %math.gcd(0, 0))
print('Calculating GCD of Zero & Non-Zero element = %d' %math.gcd(2, 0))
print('Calculating GCD of Non-Zero & Zero element = %d' %math.gcd(0, 4))

print('Calculating GCD of of Tuple Item = %d' %math.gcd(Tup[2], 4))
print('Calculating GCD of of Tuple Item = %d' %math.gcd(Tup[2], -6))
print('Calculating GCD of List Item = %d' %math.gcd(Lis[4], 5))
print('Calculating GCD of List Item = %d' %math.gcd(Lis[4], -45))

print('Calculating GCD of Multiple Number = %d' %math.gcd(10 + 20 - 12, 40))

print('Calculating GCD of String Value = ', math.gcd('2', 3))
Python GCD Function
  1. We used the Tuple and List items as the first arguments and Positive and negative integer values as the second argument for this Math function. If you observe the above screenshot, it is working perfectly on them.
  2. Next, We assigned multiple values as the first arguments, and it worked without any issue.
  3. Next, We tried Python gcd Function on String value, which returns TypeError as output.
  4. Within the Python IDE, We passed the Decimal values as the Function arguments. As we said earlier, it is returning the TypeError: ‘float’ object cannot be interpreted as an integer.