题目:寻找能被1-20整除的最小数下面是我写的程序:
class Test8 {
public static void main(String[] args) {
int s  = 1;
boolean t = false;
while(t ==false) {
for(int i=1; i<=20; i++) {
if(s%i == 0) {

t = true;
}
else {
t = false;
++s;
break;
}
}
}
System.out.println(s);




}
}但是一直在运行,貌似是个死循环,但是我调试了很多遍都不知哪里错了
求大虾指点一下希望大家写出一个更加合理和简便的算法
小弟在这里拜谢了!!

解决方案 »

  1.   

    因为能被1-20的所有数整除,那么此数必是20的倍数,故可将步长优化为20,
    而后穷举就可以了。
    检查此数是否满足条件时,从大到小比较好,因为19 与 17是质数,可以免去很多不必要的运算.public class Min {
        public static int check(long s){
         int i; 
         for(i=20;i>=1;i--)
          if(s%i!=0)
          break;
          if(i>=1) return 0;
          else return 1;
        
        }
    public static void main(String[] arsg){
       long s=20;
       while(true){
      if(check(s)==1) break;
      else s+=20;
       }
       System.out.println(s);
     }
    }
      

  2.   


        static float div(){
        
         float  s=20;
         boolean res=true;
         while(res){
         int count=0;
         for(int i=3;i<=20;i++){
             if(s%i!=0){
             break;
             }else{
             count++;
             }
             }
         if(count==18){
         res=false;
         }
         s+=20;
         }
          return s;
        }