How to condense my 9 if statements into one

  • A+
Category:Languages

I wanted to see what the smallest number divisible by all one digit numbers was and instead of looking it up I created this.

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;                                     }                                 }                             }                         }                     }                 }             }         }     } } 

As you can see, I have an if statement in an if statement x9. The code worked but I wanted to condense my if statements using an array to make my if statement like this but it didn't work.

 if (i % x[1, 2, 3, 4, 5, 6, 7, 8]) {  System.out.println(i);  break;  } 

Any suggestions?


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) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: