Thursday, April 07, 2011

How to determine the LCM of an array of numbers?

This solution exploits two properties of LCM: i) LCM(a,b) = (a.b)/GCD(a, b) and LCM(a, b, c) = LCM(a, LCM(a,b)).

package personal.puzzles;

public class LCMEuclid {

public int findLCMOfArray(int[] array) {
if (array.length == 0) {
throw new IllegalArgumentException("You cannot determine LCM of empty array");
} else if (array.length == 1) {
return array[0];
}
int first = array[0];
int second = array[1];
int lcm = findLCMOfPair(first, second);
for (int i = 2; i < array.length; ++i) {
lcm = findLCMOfPair(lcm, array[i]);
}
return lcm;
}

private int findLCMOfPair(int first, int second) {
return first * second / gcd(first, second);
}

private int gcd(int first, int second) {
while (first % second != 0) {
int tempSecond = first % second;
first = second;
second = tempSecond;
}
return second;
}

public static void main(String[] args) {
int a[] = {21, 6, 7, 11};
LCMEuclid lcmEuclid = new LCMEuclid();
System.out.println(lcmEuclid.findLCMOfArray(a));
}
}

Labels: ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home