Learn about LCM of Two Numbers in Python using Recursion in the below code example. Also, refer to the comments in the code snippet to get a detailed view about what’s actually happening.
Contents
LCM of Two Numbers in Python using Recursion
The recursive function find_gcd() will calculate the GCD of two numbers in a recursive approach and then the LCM is calculated using the below formula.
LCM(a, b) = (a*b) / GCD(a, b)
Source code:
# Python program to find the LCM using recursion
#recursive function
def find_gcd(a, b):
if(b == 0):
return a
else:
return find_gcd(b, a%b)
# inputs from user
num1 = int(input('Enter first number: '))
num2 = int(input('Enter second number: '))
# find LCM
lcm = (num1 * num2) // find_gcd(num1, num2)
# print result
print('The LCM of',num1,'and',num2,'is',lcm)
Output:
Enter first number: 6 Enter second number: 8 The LCM of 6 and 8 is 24
Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.
Similar Code : LCM of Two Numbers using GCD in Python