![](/img/trans.png)
[英]What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
[英]What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 100?
以下是我嘗試使用 BigInteger inn Java 計算從一到一百的所有數字的 LCM 的代碼。 但它不提供任何答案。
import java.math.BigInteger;
public class CommonOneToHundred {
public static void main(String[] args) {
// TODO Auto-generated method stub
BigInteger res =new BigInteger("1");
int i = 2;
while(i<=100){
res = lcm(res,BigInteger.valueOf(i));
i++;
}
System.out.println(res);
}
static BigInteger lcm(BigInteger x, BigInteger y)
{
BigInteger a;
//a = (x > y) ? x : y; // a is greater number
a = y;
while(true)
{
if(a.divide(x).equals(0) && a.divide(y).equals(0))
return a;
a = a.add(BigInteger.ONE);
}
}
}
為什么不乘以所有素數的最高冪直到 100。這是我在 python 中的代碼。
primes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97]
ans = 1
for prime in primes:
power = 0
tmp = 1
while tmp <= 100:
tmp = tmp*prime
power += 1
ans = ans * prime**(power-1)
print ans
答案是69720375229712477164533808935312303556800
。
從 1 到 100 累計使用 LCM 將花費極長的時間,即使它不會溢出BigInteger
數據類型。 嘗試不同的算法。 首先准備一個素數表 2,3,5,7,...,97,然后對 1 到 100 之間的每個數進行素數因式分解,並找出所有 100 個數中每個素數的最大冪。 最后,可能使用BigInteger
類型乘以這些質因數的冪。 答案是 2^6 * 3^4 * 5^2 * 7^2 * 從 11 到 97 的所有質數 = 69720375229712477164533808935312303556800
。 事實上,質因數分解步驟是可以省去的。 人們可以找到每個素數在 100 以內的最高冪。 無法避免BigInteger
乘法,因為數字超過了long long
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.