[ Web Proxy ]
URL:
Viewing: https://www.tutorialspoint.com/python/python_math_gcd_method.htm [Back]  [Original]

Python math.gcd() Method
Tutorials Courses Jobs Login
Selected Reading
Home Python Python math.gcd() Method

Python math.gcd() Method



The Python math.gcd() method is used to calculate the greatest common divisor (GCD) of two or more integers. The greatest common divisor is the largest positive integer that divides each of the integers without leaving a remainder.

For example, if you have two integers a = 12 and b = 8, the math.gcd(12, 8) method will return 4 because 4 is the largest positive integer that divides both 12 and 8 without leaving a remainder.

Syntax

Following is the basic syntax of the Python math.gcd() method

math.gcd(a, b)

Parameters

This method accepts the following parameters

  • a This is an integer representing the first number.

  • b This is an integer representing the second number.

Return Value

The method returns an integer, which represents the greatest common divisor of "a" and "b".

The result is always a non-negative integer, and it is the largest integer that divides both "a" and "b" without leaving a remainder. If both "a" and "b" are zero, it returns zero.

Example 1

In the following example, we are calculating the greatest common divisor of 12 and 8 using the math.gcd() method

import math
result = math.gcd(12, 8)
print("The result obtained is:",result)  

Output

The output obtained is as follows

The result obtained is: 4

Example 2

When we pass negative integer values as arguments to the gcd() method, it returns a positive integer value (GCD)

import math
result = math.gcd(-15, -10)
print("The result obtained is:",result)  

Output

Following is the output of the above code

The result obtained is: 5

Example 3

In here, we calculate the greatest common divisor of "0" and "10". Since one of the numbers is "0", the result is the absolute value of the non-zero number, which is "10"

import math
result = math.gcd(0, 10)
print("The result obtained is:",result)  

Output

We get the output as shown below

The result obtained is: 10

Example 4

In this example, we use variables "a" and "b" to store the integers "24" and "36", respectively. We then calculate their greatest common divisor

import math
a = 24
b = 36
result = math.gcd(a, b)
print("The result obtained is:",result)  

Output

The result produced is as shown below

The result obtained is: 12
python_maths.htm
Tutorix - AI Tutor [Tutorix - AI Tutor]
Print Page
Advertisements

Web Proxy Viewer  |  New URL  |  Original Page