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

tutoriel de base Python

contrôle de flux Python

Fonctions en Python

Types de données en Python

opérations de fichiers Python

objets et classes Python

date et heure Python

connaissances avancées Python

manuel de référence Python

programme Python pour trouver le LCM

Complete Python Examples

Dans ce programme, vous allez apprendre à trouver le LCM de deux nombres et à leAfficher.

Pour comprendre cet exemple, vous devriez comprendre ce qui suit :programmation PythonSujet :

Le plus petit commun multiple (LCM) de deux nombres est le plus petit entier positif divisible par les deux nombres donnés.

par exemple, le LCM est12et14pour84.

programme de calcul du LCM

# Use Python program to calculate the L.C.M. of two input numbers
def compute_lcm(x, y):
   # Choisir le nombre plus grand
   si x > y:
       greater = x
   sinon:
       greater = y
   while(True):
       si ((greater % x == 0) et (greater % y == 0)):
           lcm = greater
           break
       greater += 1
   return lcm
num1 = 54
num2 = 24
print("L.C.M. is", compute_lcm(num1, num2))

résultat de sortie

L.C.M. est 216

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

The program calculates the value of num1and num2to store the two numbers. These numbers will be passed to the compute_lcm() function. The function returns the L.C.M. 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, and then the loop continues.

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

Number1 * Number2 = L.C.M. * 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. of the 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.

Complete Python Examples