C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Python Program to Find LCMIn the following tutorial, we will learn how to find Least Common Multiple (LCM) using the Python programming language. But before we get started, let us briefly discuss about LCM. LCM: Least Common Multiple/ Lowest Common MultipleLCM stands for Least Common Multiple. It is a concept of arithmetic and number system. The LCM of two integers a and b is denoted by LCM (a,b). It is the smallest positive integer that is divisible by both "a" and "b". For example: We have two integers 4 and 6. Let's find LCM Multiples of 4 are: 4, 8, 12, 16, 20, 24, 28, 32, 36,... and so on... Multiples of 6 are: 6, 12, 18, 24, 30, 36, 42,... and so on.... Common multiples of 4 and 6 are simply the numbers that are in both lists: 12, 24, 36, 48, 60, 72,.... and so on.... LCM is the lowest common multiplier so it is 12. Since, we have understood the basic concept of the LCM, let us consider the following program to find the LCM of given integers. Example: # defining a function to calculate LCM def calculate_lcm(x, y): # selecting the greater 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 # taking input from users num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) # printing the result for the users print("The L.C.M. of", num1,"and", num2,"is", calculate_lcm(num1, num2)) Output: Enter first number: 3 Enter second number: 4 The L.C.M. of 3 and 4 is 12 Explanation: This program stores two number in num1 and num2 respectively. These numbers are passed to the calculate_lcm() function. The function returns the LCM of two numbers. Within the function, we have first determined the greater of the two numbers as the LCM can only be greater than or equal to the largest number. We then use an infinite while loop to go from that number and beyond. In every iteration, we have checked if both the numbers perfectly divide the number. If so, we have stored the number as LCM and break from the loop. Otherwise, the number is incremented by 1 and the loop continues.
Next TopicPython Program to Find HCF
|