Write a Python program to find LCM of two numbers using While Loop, Functions, and Recursion.
In Mathematics, the Least Common Multiple (LCM) of two or more integers is the smallest positive integer that is perfectly divisible by the given integer values without the remainder. For example, the LCM value of integer 2 and 3 is 12 because 12 is the smallest positive integer that is divisible by both 2 and 3 (the remainder is 0).
Python Program to find LCM of Two Numbers Example 1
This python program allows the user to enter two positive integer values. Within the Python while loop, we used If statement to check the remainder of maximum % a and maximum % b equals to zero or not. If true, LCM = maximum otherwise, skip that value.
# Python Program to find LCM of Two Numbers a = float(input(" Please Enter the First Value a: ")) b = float(input(" Please Enter the Second Value b: ")) if(a > b): maximum = a else: maximum = b while(True): if(maximum % a == 0 and maximum % b == 0): print("\n LCM of {0} and {1} = {2}".format(a, b, maximum)) break; maximum = maximum + 1
Python Program to find LCM of Two Numbers using Functions
This Python LCM program is the same as above. However, we are separating the logic using Functions
# Python Program to find LCM of Two Numbers def findlcm(a, b): if(a > b): maximum = a else: maximum = b while(True): if(maximum % a == 0 and maximum % b == 0): lcm = maximum; break; maximum = maximum + 1 return lcm num1 = float(input(" Please Enter the First Value Num1 : ")) num2 = float(input(" Please Enter the Second Value Num2 : ")) lcm = findlcm(num1, num2) print("\n LCM of {0} and {1} = {2}".format(num1, num2, lcm))
Python Program to Calculate LCM of Two Numbers using GCD
This python program finds the GCD of two numbers. Using this, we calculate LCM. Here, we are using the Temp variable to find GCD.
# Python Program to find LCM of Two Numbers num1 = float(input(" Please Enter the First Value Num1 : ")) num2 = float(input(" Please Enter the Second Value Num2 : ")) a = num1 b = num2 while(num2 != 0): temp = num2 num2 = num1 % num2 num1 = temp gcd = num1 print("\n GCD of {0} and {1} = {2}".format(a, b, gcd)) lcm = (a * b) / gcd print("\n LCM of {0} and {1} = {2}".format(a, b, lcm))
Python Program to Calculate LCM of Two Numbers using Recursion
It allows user to enter two positive integer values, and calculate the GCD of those two values by calling findgcd function recursively.
# Python Program to find LCM of Two Numbers def findgcd(a, b): if(b == 0): return a; else: return findgcd(b, a % b) num1 = float(input(" Please Enter the First Value Num1 : ")) num2 = float(input(" Please Enter the Second Value Num2 : ")) gcd = findgcd(num1, num2) print("\n GCD of {0} and {1} = {2}".format(num1, num2, gcd)) lcm = (num1 * num2) / gcd print("\n LCM of {0} and {1} = {2}".format(num1, num2, lcm))