LCM of an Array
Problem
The first line has n. The second line has n positive integers. Print the least common multiple of all of them. The answer is smaller than 2^53 in all tests.
Constraints
- 1 <= n <= 10^5
- The answer < 2^53
Examples
Input
2 4 6
Output
12
Solutions
We use lcm(x, y) = x / gcd(x, y) * y and fold the array. Dividing before multiplying avoids overflow.
/*
* Problem : Find the lcm of many numbers.
* Input : n, then n integers.
* Output : The lcm.
* Approach: lcm(x, y) = x / gcd(x, y) * y.
* Time : O(n log max)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static long solve(int[] a) {
// Step 1: The lcm of one number is the number itself.
long result = a[0];
// Step 2: Combine with each next number: lcm(x, y) = x / gcd(x, y) * y.
for (int i = 1; i < a.length; i++) {
long x = result;
long y = a[i];
while (y != 0) {
long remainder = x % y;
x = y;
y = remainder;
}
// Step 3: Now x is the gcd. Divide first, then multiply, to keep the number small.
result = result / x * a[i];
}
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
System.out.println(solve(a));
}
}
Hints (1)
- How are gcd and lcm related?