Coders Packet

L.C.M. of two numbers using division method without H.C.F demonstrating recursion in Java

By Tanisha Adhikari

This project contributes to one of the major factors of OOP's (reusing code)- The Recursion. Through a code snippet in Java generating L.C.M I have shown the working of recursion.

Hey everyone. Hope you guys are doing good. This code designed in Java is used to generate L.C.M. of two numbers using division method and without finding the H.C.F of those numbers via recursion. The logic used for the code is as demonstrated below: -

Suppose there are two numbers 12 and 18 as user input for which we have to generate the L.C.M. and we supply the first multiple as 2(Since all numbers are divisible by 1).

The code checks for the condition if the numbers are 1 or not otherwise it shifts to the condition of division.

If 12%2 == 0 and 18%2! = 0 which is false so it checks for the next condition.

If 12%2! = 0 and 18%2 == 0 which is again false it checks for the next condition.

If 12%2! =0 and 18%2! = 0 becomes false again to ultimately fall to the next condition.

That is the recursive function returns a value of (12/2,18/2,2) which is (6,9,2) for the successive recursions to follow with 2 as the least common factor between 12 and 18.

Ultimately following this logic, the recursive stack returns a value of 2*1*3*3*2=36.

So it prints the L.C.M. of 12 and 18 as 36.

Below is the attached output for reference: -

Download Complete Code


No comments yet