Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python math.gcd() Method



The Pythonmath.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, themath.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 Pythonmath.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 themath.gcd() method −

import mathresult = 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 thegcd() method, it returns a positive integer value (GCD) −

import mathresult = 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 mathresult = 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 usevariables "a" and "b" to store the integers "24" and "36", respectively. We then calculate their greatest common divisor −

import matha = 24b = 36result = 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
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp