Java Program to Find LCM of two Numbers

Java Program to Find LCM of two Numbers

What is LCM of Numbers ?

The smallest positive integer that is a multiple of two or more numbers is known as the LCM (Least Common Multiple). We can use prime factorization to find the LCM by taking the product of the highest powers of each prime factor, or we can list the multiples of each number and find the lowest one that appears in all the lists.

Steps to Find the Largest Among Three Numbers :

  1. Each integer should be divided into its prime elements.
  2. List every distinct prime factor that appears in every number.
  3. Choose the highest power that appears across all the numbers for each distinct prime factor.
  4. Multiply all the prime factors together, using the highest power for each factor.

Example to determine the LCM of 6 and 8 :

  1. Divide 6 into its prime elements to find: 6 = 2 * 3
  2. Factor 8 into its main components: 8 = 2 * 2 * 2
  3. Find the distinct prime factors: 2 and 3.
  4. Take into account the maximum power for 2 in either of the factorizations: 2^3 = 8.
  5. Choose the highest power that occurs for 3, then: 3^1 = 3.
  6. Add the prime elements together to get: LCM(6, 8) = 2^3 * 3^1 = 24.

So the LCM of 6 and 8 is 24.

Pseudo Code using while loop :

function LCM(a, b):
    lcm = max(a, b)
    while True:
        if lcm % a == 0 and lcm % b == 0:
            return lcm
        lcm += max(a, b)

Example 1 : 

Run
public class Main {
    public static void main(String[] args) {
        int a = 24, b = 36;
        int lcm = findLCM(a, b);
        System.out.println("LCM of " + a + " and " + b + " is " + lcm);
    }

    public static int findLCM(int a, int b) {
        int lcm = Math.max(a, b);
        while (true) {
            if (lcm % a == 0 && lcm % b == 0) {
                return lcm;
            }
            lcm += Math.max(a, b);
        }
    }
}

Output :

LCM of 24 and 36 is 72

Example 2 : 

Run
public class Main {
    public static void main(String[] args) {
        int a = 24, b = 36;
        int gcd = findGCD(a, b);
        int lcm = (a * b) / gcd;
        System.out.println("LCM of " + a + " and " + b + " is " + lcm);
    }

    public static int findGCD(int a, int b) {
        if (b == 0) {
            return a;
        }
        return findGCD(b, a % b);
    }
}

Output :

LCM of 24 and 36 is 72

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription