English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python basic tutorial

Python flow control

Python Functions

Python Data Types

Python file operations

Python objects and classes

Python date and time

Advanced Python knowledge

Python reference manual

Python program to find LCM

Python example大全

In this program, you will learn to find the LCM of two numbers and display it.

To understand this example, you should understand the followingPython programmingTopic:

The least common multiple (LCM) of two numbers is the smallest positive integer that is divisible by both given numbers.

For example, the LCM is12and14For84.

Program to calculate LCM

# Use Python program to calculate the L.C.M. of two input numbers
def compute_lcm(x, y):
   # Choose the larger 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 = 54
num2 = 24
print("L.C.M. is", compute_lcm(num1, num2))

output result

L.C.M. is 216

Note:To test this program, you can modify the value of num1and num2of the value.

This program calculates the value of num1and num2Two numbers are stored. These numbers will be passed to the compute_lcm() function. The function returns the LCM of the two numbers.

In the function, we first determine the larger of the two numbers because the L.C.M. can only be greater than or equal to the largest number. Then, we use an infinite while loop starting from that number.

In each iteration, we check if the two numbers are perfectly divisible by our number. If so, we store the number as LCM and exit the loop. Otherwise, the number will increase1,then the loop continues.

The above program runs slower. We can use the fact that the product of two numbers is equal to the product of the L.C.M. and G.C.D. of these numbers to improve efficiency.

Number1 * Number2 = * G.C.D.

This is a Python program that achieves this purpose.

Program to calculate LCM using GCD

# Use Python program to calculate the L.C.M. of two input numbers
# This function computes GCD 
def compute_gcd(x, y):
   while(y):
       x, y = y, x % y
   return x
# This function calculates LCM
def compute_lcm(x, y):
   lcm = (x*y)//compute_gcd(x,y)
   return lcm
num1 = 54
num2 = 24 
print("L.C.M. is", compute_lcm(num1, num2))

The output of this program is the same as before. We have two functions compute_gcd() and compute_lcm(). We need the G.C.D. numbers to calculate their L.C.M.

Therefore, the compute_lcm() function calls the compute_gcd() function to complete this operation. G.C.D. Using the Euclidean algorithm can effectively calculate the sum of two numbers.

Click here to learn more aboutCalculate GCD in PythonMore information about the method.

Python example大全