Python math.lcm() Method



The Python math.lcm() method is used to calculate the least common multiple (LCM) of two or more integers. Mathematically, the least common multiple of two integers "a" and "b", denoted as lcm(a,b), is the smallest positive integer that is divisible by both "a" and "b".

The LCM can be calculated using the relationship between the LCM and the greatest common divisor (GCD). If gcd(a,b) represents the greatest common divisor of "a" and "b", then −

lcm(a, b)\:=\:\frac{|a\:\times\:b|}{gcd(a,\:b)}

Where, |a × b| denotes the absolute value of the product of "a" and "b". For example, if a = 6 and b = 8, then lcm(6,8) can be calculated as follows −

  • gcd(6, 8) = 2
  • |6 × 8| = 48
  • lcm(6, 8) = 48/2 = 24

Thus, lcm(6,8)=24, meaning that the least common multiple of 6 and 8 is 24.

Note: To use this function, you need to import math module.

Syntax

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

math.lcm(a, b)

Parameter

This method accepts integers as a parameter for which you want to find the least common multiple (LCM).

Return Value

The method returns the least common multiple of the given integer values.

Example 1

In the following example, we are calculating the LCM of "12" and "15" using the math.lcm() method −

import math
result = math.lcm(12, 15)
print("The result obtained is:",result)         

Output

The output obtained is as follows −

The result obtained is: 60

Example 2

Here, we calculate the LCM of negative integer values "-6" and "-9" using the math.lcm() method −

import math
result = math.lcm(-6, -9)
print("The result obtained is:",result)  

Output

Following is the output of the above code −

The result obtained is: 18

Example 3

The LCM of any number and 0 is always 0. Now, we calculate the LCM of "0" and "5" using the math.lcm() method −

import math
result = math.lcm(0, 5)
print("The result is:",result)  

Output

We get the output as shown below −

The result obtained is: 0

Example 4

In this example, we use variables "a" and "b" to store the numbers "8" and "12" respectively. We then calculate the LCM of "a" and "b" using the math.lcm() method −

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

Output

The result produced is as shown below −

The result obtained is: 24
python_maths.htm
Advertisements