How to condense my 9 if statements into one [closed]
At first you would think you can test all of them at once by placing the product of 2 through 9 on the right side of the %
operator.
if (i % (2 * 3 * 4 * 5 * 6 * 7 * 8 * 9) == 0)
But because certain numbers include previous numbers in their factorization, you should use a lower number, specifically, the least common multiple. 8 is a multiple of 2 and 4, 9 is a multiple of 3, and if 8 and 9 are in the product, then 6 (2 * 3) is covered too.
if (i % (5 * 7 * 8 * 9) == 0)
That turns out to be 2520, which is the least common multiple. It would much more readable to use 2520
and explain in a comment why this number is used.
/**
* 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;
I've declared a constant and I'll use it here:
if (i % LCM_2_THRU_9 == 0)
Try this.
for (int i = 100; i < 10000; ++i) {
int x = i;
if (IntStream.of(2, 3, 4, 5, 6, 7, 8, 9).allMatch(k -> x % k == 0)) {
System.out.println(i);
break;
}
}
-> 2520
Or you can write this as one statement.
int result = IntStream
.range(100, 10000)
.filter(i -> IntStream.of(2, 3, 4, 5, 6, 7, 8, 9).allMatch(k -> i % k == 0))
.findFirst()
.getAsInt();
System.out.println(result);
-> 2520