Java Program to Calculate the LCM of Two Numbers

In this example, we are giving a program to calculate the LCM(Lowest common multiple) of two numbers.


To calculate the LCM:

  1. # To calculate the LCM
  2. public class LCM {
  3. public static void main(String[] args) {
  4. int n1 = 12, n2 = 15, lcm;
  5. lcm = (n1 > n2) ? n1 : n2;
  6. while(true) {
  7. if( lcm % n1 == 0 && lcm % n2 == 0) {
  8. System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm);
  9. break;
  10. }
  11. ++lcm;
  12. }
  13. }
  14. }

Output:

G.C.D of 49 and 7 is 7