LCM using while Loop and if Statement

Java Programming Language Decision Making and Looping in java (Article) Decision Making and Looping in java (Program)

17

Program:

public class Main {
  public static void main(String[] args) {

    int n1 = 72, n2 = 120, lcm;

    // maximum number between n1 and n2 is stored in lcm
    lcm = (n1 > n2) ? n1 : n2;

    // Always true
    while(true) {
      if( lcm % n1 == 0 && lcm % n2 == 0 ) {
        System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm);
        break;
      }
      ++lcm;
    }
  }
}

Output:

The LCM of 72 and 120 is 360.

Explanation:

This Java program calculates the Least Common Multiple (LCM) of two numbers using a while loop.

Here's a breakdown of how the code works:

  1. Initialization:

    • Two integers n1 and n2 are initialized with values 72 and 120 respectively.
    • Another integer lcm is initialized without a value.
  2. Finding the Maximum:

    • The program compares n1 and n2 using the ternary operator (? :) and assigns the maximum of the two numbers to the variable lcm.
    • This step ensures that the variable lcm initially holds the larger of the two numbers.
  3. Calculating the LCM:

    • The program enters a while loop with the condition true, indicating an infinite loop.
    • Inside the loop, it checks if lcm is divisible by both n1 and n2 using the modulo operator (%).
    • If lcm is divisible by both n1 and n2, it prints the LCM using the printf method and breaks out of the loop.
    • If lcm is not divisible by both n1 and n2, it increments lcm by 1 and continues the loop.
  4. Output:

    • The program prints out the calculated LCM of n1 and n2 using the printf method.

In summary, this program calculates the LCM of two given numbers (n1 and n2) using a while loop and prints the result. It starts with the larger of the two numbers as the initial guess for the LCM and increments it until it finds a number that is divisible by both n1 and n2.


This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.