求一百以内的素数不包括1,在时间、速度上面要快!!不多说直接上代码。
第一种:
public class AA {
public static void main(String[] args) {
long start = System.currentTimeMillis();
//如果要求100以内的质数
for (int i = 1; i < 100; i+=2) {
boolean zhishu = true;
//每个数除以它之前的数,是否能整出
for (int j = 2; j <= Math.sqrt(i) ; j++) {
if (i % j == 0) {
zhishu = false;
break;//可以省去,但是效率会下降
}
}
if (zhishu) {
System.out.println(i);
}
}
System.out.println(System.currentTimeMillis()-start);
}
}
运行结果:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97运行时间是:3
第二种:
public class AA {
public static void main(String[] args) {
long start = System.currentTimeMillis();
//如果要求100以内的质数 将1000改为100即可
for (int i =2 ; i < 100; i++) {
boolean zhishu = true;
//每个数除以它之前的数,是否能整出
for (int j = 2; j <=Math.sqrt(i); j++) {
if (i % j == 0) {
zhishu = false;
break;//可以省去,但是效率会下降
}
}
if (zhishu) {
System.out.println(i);
}
}
long end = System.currentTimeMillis()-start;
System.out.println("运行时间是:" + end);
}
}
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97运行时间是:1
结果和第一种基本一样,但是当你把100改成10000,再试一下,时间相差基本一半。
第三种 使用标记位:
public static void main(String[] args) {
long start=System.currentTimeMillis();
lable:for(int i=2;i<=1000;i++){
for(int j=2;j<Math.sqrt(i);j++){
if(i%j==0){
continue lable;
}
}
System.out.println(i);
}
long end=System.currentTimeMillis();
System.out.println(end-start);//63
}
这个效率最高,并且代码简洁明了。 推荐使用这种!!