/* 连续数的公倍数 为什么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
作者:hanshileiai 发表于2013-4-23 14:57:46 原文链接
阅读:48 评论:0 查看评论