LCM of an array of numbers in Java

Java8Java Programming Javascript

L.C.M. or Least Common Multiple of two values, is the smallest positive value which the multiple of both values.

For example multiples of 3 and 4 are:

3 → 3, 6, 9, 12, 15 ...

4 → 4, 8, 12, 16, 20 ...

The smallest multiple of both is 12, hence the LCM of 3 and 4 is 12.

Program

Following example computes the LCM of array of numbers.

Live Demo

public class LCMofArrayOfNumbers {
   public static void main(String args[]) {
      int[] myArray = {25, 50, 125, 625};
      int min, max, x, lcm = 0;
     
      for(int i = 0; i<myArray.length; i++) {
         for(int j = i+1; j<myArray.length-1; j++) {
            if(myArray[i] > myArray[j]) {
               min = myArray[j];
               max = myArray[i];
            } else {
               min = myArray[i];
               max = myArray[j];
            }
            for(int k =0; k<myArray.length; k++) {
               x = k * max;
               if(x % min == 0) {
                  lcm = x ;
               }
            }
         }
      }
      System.out.println("LCM of the given array of numbers : " + lcm);
   }
}

Output

LCM of the given array of numbers : 250
raja
Updated on 25-Jun-2020 11:59:39

Advertisements