How to Find the Least Common Multiple in Python


 1. Introduction

In this example we will show how to get the least common multiple (LCM) of two numbers in Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

# Least common multiple

# defined function
def lcm(x, y):
    # Get the larger one of x and y as starting number
    if x > y:
        greater = x
    else:
        greater = y

    while (True):
        if ((greater % x == 0) and (greater % y == 0)):
            lcm = greater
            break
        greater += 1

    return lcm

num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

print("Least common multiple: ", lcm(num1, num2))
Enter the first number: 12
Enter the second number: 15
Least common multiple: 60

Enter the first number: 6
Enter the second number: 7
Least common multiple: 42
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments