I have method which should give the LCM of multiple numbers. It works with Java's reduce() method so the numbers 1,2,3 gives the LCM of 6, which is correct:
int lcmAnswer = Arrays.stream(numbers).reduce(1, (a, b) -> {
int total = lcmm(a, b);
return total;
}
);
System.out.println(lcmAnswer); // LCM(1, 2, 3) = 6
However if I don't use Java's reduce() method then the numbers 1,2,3 don't give me the LCM of 6. It gives me LCM(1, 2, 3) = 8, which is wrong:
int[] numbers = {1, 2, 3};
System.out.println(lcmm(1,2,3)); // LCM(1, 2, 3) = 8, which is wrong
private static int lcmm(int... numbers) {
int sum = 0;
for (int i = 0; i<numbers.length -1; i++) {
int curr = numbers[i];
int next = numbers [i+1];
sum += lcm(curr, next);
}
return sum;
}
private static int lcm(int p, int q) {
// Return lowest common multiple.
return p * q / gcd(p, q);
}
private static int gcd(int p, int q) {
//Return greatest common divisor using Euclid's Algorithm.
int temp;
while (q != 0) {
temp = q;
q = p % q;
p = temp;
}
return p;
}
Does someone has any idea what I'm doing wrong?