你需要反过来循环,如果你愿意,你不需要检查是否% 1
可以使用最高的素数。如果它是 4 和 5 的倍数,它也必须是 20 的倍数;)
由于它必须是所有素数的倍数,您只需检查 2*3*5*7*11*13*17*19 的倍数。这将使它变得更快,更快。
没有上限,所以你不需要添加一个。counter < Integer.MAX_VALUE
如果你愿意,你可以做到。
您可以计算这些因素必须是什么,而不是使用蛮力。
public class CommonMultipleMain {
static final int MAX = Integer.getInteger("max", 1000);
public static void main(String... ignored) {
// warmup
getLowestMultipleOf(60);
long start = System.nanoTime();
BigInteger bi = getLowestMultipleOf(MAX);
long time = System.nanoTime() - start;
System.out.println("Smallest number which has factors up to " + MAX + " took " + time / 1000 + " us, is " + bi);
}
private static BigInteger getLowestMultipleOf(int max) {
int[] maxFactorCount = new int[max + 1];
for (int i = 2; i <= max; i++) {
int[] factors = getFactorsFor(i);
for (int j = 2; j < factors.length; j++)
if (maxFactorCount[j] < factors[j])
maxFactorCount[j] = factors[j];
}
BigInteger bi = BigInteger.ONE.shiftLeft(maxFactorCount[2]);
for (int i = 3; i <= max; i += 2) {
int exponent = maxFactorCount[i];
switch (exponent) {
case 0:
break;
case 1:
bi = bi.multiply(BigInteger.valueOf(i));
break;
default:
bi = bi.multiply(BigInteger.valueOf(i).pow(exponent));
break;
}
}
return bi;
}
private static int[] getFactorsFor(int i) {
int[] factors = new int[i + 1];
while ((i & 1) == 0) {
i >>= 1;
factors[2]++;
}
for (int j = 3; j * j <= i; j += 2) {
while (i % j == 0) {
i /= j;
factors[j]++;
}
}
if (i > 1)
factors[i]++;
return factors;
}
}
印刷
Smallest number which has factors up to 1000 took 15005 us, is 7128865274665093053166384155714272920668358861885893040452001991154324087581111499476444151913871586911717817019575256512980264067621009251465871004305131072686268143200196609974862745937188343705015434452523739745298963145674982128236956232823794011068809262317708861979540791247754558049326475737829923352751796735248042463638051137034331214781746850878453485678021888075373249921995672056932029099390891687487672697950931603520000
计算到这个数字需要比宇宙年龄更长的时间,但通过计算,它所用的时间比眨眼所用的时间要少。