Thursday, 26 December 2024

Day 60: Python Program to Find Lcm of Two Number Using Recursion

 


def find_lcm(a, b):

    def find_gcd(a, b):

        if b == 0:

            return a

        else:

            return find_gcd(b, a % b)

    return abs(a * b) // find_gcd(a, b)

num1 = int(input("Enter the first number: "))

num2 = int(input("Enter the second number: "))

lcm = find_lcm(num1, num2)

print(f"The LCM of {num1} and {num2} is {lcm}.")

#source code --> clcoding.com 

Code Explanation:

1. def find_lcm(a, b):
This defines a function find_lcm that takes two parameters, a and b, representing the two numbers for which we want to calculate the LCM.

2. def find_gcd(a, b):
Inside the find_lcm function, there is a nested helper function find_gcd to calculate the GCD of two numbers.
The function uses recursion:
Base Case: If b == 0, return a as the GCD.
Recursive Case: Call find_gcd(b, a % b) until b becomes 0.
This is an implementation of the Euclidean Algorithm to compute the GCD.

3. return abs(a * b) // find_gcd(a, b)
Once the GCD is determined, the formula for calculating LCM is used:
LCM
(๐‘Ž,๐‘)=∣๐‘Ž×๐‘∣/GCD(๐‘Ž,๐‘)
​abs(a * b) ensures the product is non-negative (handles potential negative input).
// is used for integer division to compute the LCM.

4. num1 = int(input("Enter the first number: "))
Takes input from the user for the first number, converts it to an integer, and stores it in num1.

5. num2 = int(input("Enter the second number: "))
Takes input from the user for the second number, converts it to an integer, and stores it in num2.

6. lcm = find_lcm(num1, num2)
Calls the find_lcm function with num1 and num2 as arguments.
The LCM of the two numbers is stored in the variable lcm.

7. print(f"The LCM of {num1} and {num2} is {lcm}.")
Outputs the calculated LCM using an f-string for formatted output.

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (63) AI (34) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (174) C (77) C# (12) C++ (82) Course (67) Coursera (228) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (21) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (60) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (941) Python Coding Challenge (378) Python Quiz (34) Python Tips (2) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (4) Software (17) SQL (42) UX Research (1) web application (8) Web development (4) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses