2 4 6 3 2 5 7
12 70
分析:兩個數的最小公倍數 lcm( x , y ) = x * y / gcd( x , y )。其中 gcd() 是這兩個數的最大公約數,可以采用“輾轉相除法”求解。所以這題的關鍵是求最大公約數。
import java.util.Scanner; public class Main { // 最大公約數 static long gcd(long a, long b) { long remainder = a % b; while (remainder != 0) { a = b; b = remainder; remainder = a % b; } return b; } // 最小公倍數 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); } } }