English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Neste programa, você aprenderá a encontrar o LCM de dois números e mostrá-lo.
Para entender este exemplo, você deve saber o seguinteprogramação PythonTema:
o menor número positivo que pode ser dividido completamente pelos dois números dados, que é o menor múltiplo comum dos dois números (LCM).
por exemplo, o LCM é12e14para84.
# Use Python program to calculate the L.C.M. of two input numbers def compute_lcm(x, y): # Escolher o número maior se x > y: maior = x senão: maior = y enquanto(True): se((maior % x == 0) e (maior % y == 0)): lcm = maior quebrar maior += 1 return lcm num1 = 54 num2 = 24 print("L.C.M. is", compute_lcm(num1, num2))
o resultado de saída
O L.C.M. é 216
Note:}To test this program, you can modify the value of num1and num2The value.
This 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 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, and then continue the loop.
The above program runs slowly. We can use the fact that the product of two numbers is equal to the product of the L.C.M. and the G.C.D. of these numbers to improve efficiency.
Number1 * Number2 = * G.C.D.
This is a Python program that achieves this purpose.
# 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 calculate the sum of two numbers efficiently.
Click here to learn more aboutCalculate GCD in PythonMore information about the method.