0

我想知道是否有可能为此编写最少的代码:

for (int x = 1; x < 10; x++){    
      /*I want to replace this condition with (x%number == 0) 
        instead of writing out condition for every number, but 
        it did not work with for (int number = 1; number <= 3; number++)
        in (x%number == 0), as it prints out every x and number 
      */
    if ((x%1) == 0 && (x%2) == 0 & (x%3) == 0){
       System.out.println(success!);
    }    
}
4

3 回答 3

3

我认为
x % a == 0 && x % b == 0 && x % c == 0
等于
x % (a * b * c) == 0

UPDATE
乘法不正确,您需要使用LCMx % lcm(a, b, c)

于 2012-08-18T12:38:24.997 回答
1

这就是让计算机科学教授高兴的必要条件:

for (int x = 1; x < 10; x++){    
    boolean success = true;
    for (int number = 1; number <= 3; number++) {
        if ((x % number) != 0) {
            success = false;
        }
    }
    if (success) {
       System.out.println("success!");
    }    
}

尽管请注意: (x % 1) 始终为 0。

根据我的“避免嵌套循环”规则,这就是你需要让我开心的东西:

for (int x = 1; x < 10; x++) {
    if (testNumber(x)) 
        System.out.println(x + " success!");
    }
}

private static boolean testNumber(int x) {
    for (int number = 1; number <= 3; number++) {
        if ((x % number) != 0) {
            return false;
        }
    }
    return true;
}
于 2012-08-18T13:10:18.473 回答
1

看一看 :

for (int x = 1; x < 10; x++){
  boolean flag = false;
    for(int num = 1; num <= 3; num++){
       if ((x%num) == 0 ){
          flag = true;
       }else{
          flag = false;
          break;
       }
    }
    if(flag){
            System.out.println(x + " success!");
    }
}

输出 :

6 success!

我知道代码看起来有点吓人,但适用于任何价值xnum

于 2012-08-18T12:38:42.080 回答