原题:java程序用来判断1-100之间的整数a是否是素数,逻辑正确吗?
public boolean isFactor(int a)throws Exception{
if(a<1 || a>100)throw new Exception("a is not between 1 and 100");
for(int i=2;i<=10;i++){
if(a % i==0)return false;
}
return true;
}
改正:
1.循环应该是 (int i = 2; i <= Math.sqrt(a); i++)
否则2-10之间没素数了
2.还有if(a<1 这个应该改成a<2,因为1不用判断
public static boolean isfactor(int a) throws Exception {
if (a < 1 || a > 100)
throw new Exception("a is not between 1 and 100");
for (int i = 2; i <= Math.sqrt(a); i++) {
if (a % i == 0)
return false;
}
return true;
}
main
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
if (isfactor(8)) {
System.out.print("ok");
} else {
System.out.print("not ok");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}