我想看看能被所有一位数字整除的最小数字是多少,而不是查找它,我创建了这个。
public static void main(String[] args) {
for (int i = 100; i < 10000; i++) {
if (i % 2 ==0) {
if (i % 3 ==0) {
if (i % 4 ==0) {
if (i % 5 ==0) {
if (i % 6 ==0) {
if (i % 7 ==0) {
if (i % 8 ==0) {
if (i % 9 ==0) {
System.out.println(i);
break;
}
}
}
}
}
}
}
}
}
}
如您所见,我在 if 语句 x9 中有一个 if 语句。该代码有效,但我想使用数组压缩我的 if 语句以使我的 if 语句像这样,但它不起作用。
if (i % x[1, 2, 3, 4, 5, 6, 7, 8]) {
System.out.println(i);
break;
}
有什么建议吗?
最佳答案
起初你会认为你可以通过将 2 到 9 的乘积放在 %
运算符的右侧来一次测试所有这些。
if (i % (2 * 3 * 4 * 5 * 6 * 7 * 8 * 9) == 0)
但由于某些数字在其因式分解中包含先前的数字,因此您应该使用较小的数字,特别是最小公倍数。 8 是 2 和 4 的倍数,9 是 3 的倍数,如果乘积中有 8 和 9,那么 6 (2 * 3) 也包括在内。
if (i % (5 * 7 * 8 * 9) == 0)
结果是 2520,这是最小公倍数。使用 2520
并在评论中解释为什么使用这个数字会更易读。
/**
* The goal is to test if the number is a multiple of all integers
* from 2 through 9. Mathematically, the least common multiple to is a
* multiple of all its input numbers. Here, the LCM of 2, 3, ..., 9 is 2520.
*/
public static final int LCM_2_THRU_9 = 2520;
我已经声明了一个常量,我将在这里使用它:
if (i % LCM_2_THRU_9 == 0)
关于java - 如何将我的 9 个 if 语句压缩为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50107150/