Lowest Common Multiple Plus
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 31279 Accepted Submission(s): 12710
Problem Description
求n个数的最小公倍数。
Input
输入包含多个测试实例,每个测试实例的开始是一个正整数n,然后是n个正整数。
Output
为每组测试数据输出它们的最小公倍数,每个测试实例的输出占一行。你可以假设最后的输出是一个32位的整数。
Sample Input
2 4 6
3 2 5 7
Sample Output
12
70
分析
两个数的最小公倍数 lcm( x , y ) = x * y / gcd( x , y )。其中 gcd() 是这两个数的最大公约数,可以采用“辗转相除法”求解。所以这题的关键是求最大公约数。
算法代码
import java.util.Scanner;
public class Main {
// 最大公约数
private static long gcd(long a, long b) {
long remainder = a % b;
while (remainder != 0) {
a = b;
b = remainder;
remainder = a % b;
}
return b;
}
// 最小公倍数
private static long lcm(long a, long b) {
return a * b / gcd(a, b);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
int n = scanner.nextInt();
long temp = 1;
for (long i = 0; i < n; i++) {
long num = scanner.nextLong();
temp = lcm(temp, num);
}
System.out.println(temp);
}
}
}