/* 连续数的公倍数
为什么1小时有60分钟,而不是100分钟呢?这是历史上的习惯导致。
但也并非纯粹的偶然:60是个优秀的数字,它的因子比较多。
事实上,它是1至6的每个数字的倍数。即1,2,3,4,5,6都是可以除尽60。
我们希望寻找到能除尽1至n的的每个数字的最小整数。
不要小看这个数字,它可能十分大,比如n=100, 则该数为:
69720375229712477164533808935312303556800
请编写程序,实现对用户输入的 n (n<100)求出1~n的最小公倍数。
例如:
用户输入:
6
程序输出:
60
用户输入:
10
程序输出:
2520
*/
import java.math.BigInteger;
import java.util.Scanner;
public class 连续数的公倍数 {
// 得到最大公约数(辗转相除)
public static BigInteger gdc(BigInteger m,BigInteger n) {
BigInteger r = m.mod(n);
while(r.compareTo(BigInteger.ZERO)!=0){
m = n;
n = r;
r = m.mod(n);
}
return n;
}
public static BigInteger f(BigInteger m,BigInteger n){
if(n.compareTo(BigInteger.ONE)==0){
return m; // n到最后
}else{
m = m.multiply(n).divide(gdc(m, n)); // 得到最小公倍数
return f(m,n.subtract(BigInteger.ONE));
}
}
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("输入的 n (n<100)");
BigInteger m = scan.nextBigInteger();
System.out.println(f(m,m.subtract(BigInteger.ONE)));
}
}
运行结果:
输入的 n (n<100)
100
69720375229712477164533808935312303556800
方法二:
import java.math.BigInteger;
public class 连续公倍数 {
// 求能除尽1~n 每个数字的最小整数
public static BigInteger f(int n) {
int[] x = new int[n + 1];
for (int i = 1; i <= n; i++)
x[i] = i;
for (int i = 2; i < n; i++) {
for (int j = i + 1; j <= n; j++) {
if(x[j] % x[i]==0) x[j] = x[j]/x[i]; // 填空1
}
}
BigInteger m = BigInteger.ONE;
for (int i = 2; i <= n; i++) {
m = m.multiply(BigInteger.valueOf(x[i])); // 填空2
}
return m;
}
public static void main(String[] args) {
System.out.println(f(100));
}
}
运行结果:
69720375229712477164533808935312303556800