连续数的公倍数 为什么1小时有60分钟,而不是100分钟呢?这是历史上的习惯导致。事实上,它是1至6的每个数字的倍数。即1,2,3,4,5,6都是可以除尽60。

/*	连续数的公倍数
为什么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


  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值