Python Tutorials

Python Programs

Python Find LCM


Python Find LCM

In this tutorial, we will learn how to find the Least Common Multiple (LCM) of two numbers in Python. We will cover the basic concept of LCM and implement functions to perform the calculation using both the built-in math library and a regular method.


What is LCM

The Least Common Multiple (LCM) of two or more integers is the smallest positive integer that is divisible by each of the integers. For example, the LCM of 4 and 5 is 20.


Syntax

The syntax to find the LCM of two numbers in Python can be done in two ways:

import math

def find_lcm_math(a, b):
    return abs(a * b) // math.gcd(a, b)

def find_lcm_regular(a, b):
    greater = max(a, b)
    while True:
        if greater % a == 0 and greater % b == 0:
            return greater
        greater += 1


Finding the LCM of two numbers using the math library

We can use the built-in math library in Python to find the LCM of two numbers.

For example,

  1. Import the math module.
  2. Define a function named find_lcm_math that takes two parameters a and b.
  3. Calculate the LCM using the formula abs(a * b) // math.gcd(a, b).
  4. Return the result.
  5. Call the function with sample values and print the result.

Python Program

import math

def find_lcm_math(a, b):
    return abs(a * b) // math.gcd(a, b)

# Find the LCM of 4 and 5 using the math library
result = find_lcm_math(4, 5)

# Print the result
print('LCM of 4 and 5 using math library is', result)

Output

LCM of 4 and 5 using math library is 20


Finding the LCM of two numbers using a regular method

We can use a regular method to find the LCM of two numbers by iterating through multiples.

For example,

  1. Define a function named find_lcm_regular that takes two parameters a and b.
  2. Determine the greater of the two numbers.
  3. Use a while loop to find the first number that is divisible by both a and b.
  4. Return the result.
  5. Call the function with sample values and print the result.

Python Program

def find_lcm_regular(a, b):
    greater = max(a, b)
    while True:
        if greater % a == 0 and greater % b == 0:
            return greater
        greater += 1

# Find the LCM of 4 and 5 using the regular method
result = find_lcm_regular(4, 5)

# Print the result
print('LCM of 4 and 5 using regular method is', result)

Output

LCM of 4 and 5 using regular method is 20