java输出100以内的质数
class Ab{
public static void main(String[] args){
boolean isFlag = true;
for (int i = 2;i <= 100; i++){
for(int j = i-1; j>1; j--){
if(i % j == 0){
isFlag = false;}
}
if(isFlag == true){
System.out.println(i + "是质数");
}
isFlag = true;
}
}
}
或者是这样
class Ab{
public static void main(String[] args){
for (int i = 2;i <= 100; i++){
boolean isFlag = true;
for(int j = i-1; j>1; j--){
if(i % j == 0){
isFlag = false;}
}
if(isFlag == true){
System.out.println(i + "是质数");
}
}
}
}
优化方式3:
class Ab{
public static void main(String[] args){
long start = System.currentTimeMillis();
for (int i = 2;i <= 10000; i++){
boolean isFlag = true;
for(int j = i-1; j>= Math.sqrt(i); j--){
if(i % j == 0){
isFlag = false;
break;
}
}
if(isFlag == true){
System.out.println(i + "是质数");
}
}
long end = System.currentTimeMillis();
System.out.print("程序检索所有质数花费的时间:" + (end - start));
}
}
|