LCM Of Two Numbers In Java With Advanced Examples

This article is about the LCM of Two Numbers In Java, this is the smallest positive integer that can be perfectly divided by both numbers (without remainder). In addition, LCM stands for lowest common multiple, smallest common multiple, and least common denominator.

Furthermore, I will also provide an advanced example of how to find the LCM of two numbers using Java and provide a well-detailed explanation to help you understand this topic with ease.

LCM of two numbers in Java with advanced examples
LCM of two numbers in Java with advanced examples

What is LCM?

In Java, LCM is also known as (Lowest Common Multiple). This is the smallest number which is divisible by both numbers. It plays a vital role for adding, comparing two or more fractions, and subtracting one or more numbers. 

For instance, LCM is used for planets. If you want to know when all the planets which move in different orbits and turn at different speeds will come together and crash into each other, or when all the trains going in different directions and at different speeds meet at a junction.

Why we need to learn LCM in Java?

The answer is simple LCM plays a very important role when adding, subtracting, and comparing two or more fractions. it’s an iterative process that uses a few basic facts.

In addition, LCM can help find the answer quickly, saving time during exams. L.C.M. is important for solving problems at racetracks, traffic lights, and other places.

Ways to find the LCM of two numbers

The following listed below are ways to find the LCM of two numbers with advanced examples.

  • Using GCD to find the LCM
  • LCM without GCD
  • Using while loop and if statement
  • Using recursion
  • Using java.util.Scanner
  • Using function

Example program to calculate LCM using GCD

The following below shows an example of calculating LCM using GCD of two numbers. We declared a variable named number1 and number2 which we also use for loop. After we calculate the GCD, we can now use the formula to easily calculate the LCM.

public class Main {

    public static void main(String[] args) {



        int number1 = 26, number2 = 233, gcd = 1;



        for (int i = 1; i <= number1 && i <= number2; ++i) {

            // Checks if i is factor of both integers

            if (number1 % i == 0 && number2 % i == 0)

                gcd = i;

        }

        int lcm = (number1 * number2) / gcd;

        System.out.printf("The LCM of %d and %d is %d.", number1, number2, lcm);

    }

}

Output:

The LCM of 26 and 233 is 6058

Example program to calculate LCM without GCD

The following program will show you how to calculate LCM without GCD. The way to do it is to start with the larger number and keep adding one to it until the smaller number divides the result perfectly divisible in prime factors.

// Java program to find LCM of 2 numbers

// without using 0 GCD

//with common multiple lcm

import java.io.*;

import java.lang.*;

public class PIES {

    // Function to return LCM of two numbers

    public static int findLCM(int x, int b) {

        int lar = Math.max(x, b);

        int small = Math.min(x, b);

        for (int i = lar;; i += lar) {

            if (i % small == 0)

                return i;

        }

    }


    // Driver program to test above function

    public static void main(String[] argc) {

        int x = 26, b = 233;

        System.out.println("LCM of " + x + " and " +

            b + " is " + findLCM(x, b));
    }

}

Output:

LCM of 26 and 233 is 6058

Example program to calculate LCM using while loop and if statement

The following program below uses a while loop to find the LCM. First we declare 2 variables, namely number1 and number2.

Furthermore, we instantiate lcm to the two numbers that are the largest, because LCM can’t be less than the largest number.

The infinite while loop is still executing(while (true)), so the program is still checking if lcm is perfectly dividing both number1 and number2 or not.

If it does, the LCM has been found. We print the LCM and then use the break statement to get out of the while loop.

If not, we add 1 to lcm and try again to see if it can be divided by two.

public class Main {

    public static void main(String[] args) {

        int number1 = 26, number2 = 233, lcm;

        // maximum number between n1 and n2 is stored in lcm

        //n1 n2 lcm

        lcm = (number1 > number2) ? number1 : number2;

        // Always true

        while (true) {

            if (lcm % number1 == 0 && lcm % number2 == 0) {

                System.out.printf("The LCM of %d and %d is %d.", number1, number2, lcm);

                break;

            }

            ++lcm;

        }

    }

}

Output:

The LCM of 26 and 233 is 6058.

Example program to find LCM using recursion

Before we begin, let us first define recursion, which is the method of calling one function from another. With this method, you can break down hard problems into smaller ones that are easier to solve.

import java.util.*;

public class PIES {

    //driver code  

    //class main public static

    public static void main(String args[]) {

        int g, y;

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the first number: ");

        g = sc.nextInt();

        System.out.print("Enter the second number: ");

        y = sc.nextInt();

        System.out.println("LCM of " + g + " and " + y + " is " + findLcm(g, y));

    }

    //function that finds GCD of the number  

    //string args int

    static int findGcd(int g, int y) {

        if (g == 0)

            //returns y is x==0  

            return y;

        //calling function that returns GCD  

        return findGcd(y % g, g);

    }

    //function finds the LCM  

    static int findLcm(int g, int y) {

        //returns the LCM   

        return (g / findGcd(g, y)) * y;

    }

}

Output:

Enter the first number: 26

Enter the second number: 233

LCM of 26 and 233 is 6058

Example program to find LCM using scanner

The following program shows how to find LCM using a scanner. A java.util.Scanner class is a simple text scanner that can read simple types and strings using regular expressions input by the user.

import java.util.Scanner;

public class PIESLCM {

    public static void main(String args[]) {

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the first number: ");

        int g = sc.nextInt();

        //reads an integer from the user  

        System.out.print("Enter the second number: ");

        //reads an integer from the user  

        int y = sc.nextInt();

        //logic for finding lcm of both numbers  

        int i;

        //find the largest between two numbers x and y and assigns the large number to the variable a  

        int a = (g > y) ? g : y;



        for (i = a; i <= g * y; i = i + a) {

            //returns true if both conditions are true  

            if (i % g == 0 && i % y == 0)

                break;

        }

        //prints the result  

        System.out.println("LCM of " + g + " and " + y + " is: " + i);

    }

}

Output:

Enter the first number: 26

Enter the second number: 233

LCM of 26 and 233 is: 6058

Example program to find LCM using function

The following program shows how to find LCM using a function. In Java, the word (method) means the same thing as (function) does in other programming languages.

A function is a part of a program that can be used more than once. It is also called a procedure or subroutine.

import java.util.Scanner;

public class PIES {

    public static void main(String args[]) {

        int x, y, max, step, lcm = 0;

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter first number ::");

        x = sc.nextInt();

        System.out.println("Enter second number ::");

        y = sc.nextInt();



        if (x > y) {

            max = step = x;

        } else {

            max = step = y;

        }



        while (x != 0) {

            if (max % x == 0 && max % y == 0) {

                lcm = max;

                break;

            }

            max += step;

        }

        System.out.println("LCM of given numbers is :: " + lcm);

    }

}

Output:

Enter first number :: 26
Enter second number :: 233
LCM of given numbers is :: 6058

Conclusion

I hope this article has helped you learn a lot. Check out my previous and latest articles for more life-changing tutorials which could help you a lot.

Leave a Comment