Java优化之输出十万以内的质数
(1)未经优化时所耗费的时间:
public class PrimeNumber {
public static void main(String[] args) {
long start = System.currentTimeMillis();
boolean flag = false;
for(int i = 2; i <= 100000; i++){
for(int j = 2; j < i; j++){
if(i % j == 0){
flag = true;
}
}
if(flag == false)
System.out.print(i+" ");
flag = false;
}
long end = System.currentTimeMillis();
System.out.println("\n"+(end - start));
}
}
其所耗费的时间为:27038ms
(2)优化一:内层循环的判断,当false已经为true的时候,即可跳出内层循环
public class PrimeNumber {
public static void main(String[] args) {
long start = System.currentTimeMillis();
boolean flag = false;
for(int i = 2; i <= 100000; i++){
for(int j = 2; j < i; j++){
if(i % j == 0){
flag = true;
break;
}
}
if(flag == false)
System.out.print(i+" ");
flag = false;
}
long end = System.currentTimeMillis();
System.out.println("\n"+(end - start));
}
}
其所耗费的时间为:2424ms
(3)优化二:内层循环只需循环到i的根号时,即可结束(注意包括i的根号)
public class PrimeNumber {
public static void main(String[] args) {
long start = System.currentTimeMillis();
boolean flag = false;
for(int i = 2; i <= 100000; i++){
for(int j = 2; j <= Math.sqrt(i); j++){
if(i % j == 0){
flag = true;
break;
}
}
if(flag == false)
System.out.print(i+" ");
flag = false;
}
long end = System.currentTimeMillis();
System.out.println("\n"+(end - start));
}
}
其所耗费的时间为:191ms
(4)也可以使用标签实现:
public class PrimeNumber2 { public static void main(String[] args) { long start = System.currentTimeMillis(); label1: for(int i = 2; i <= 100000; i++){ for(int j = 2; j <= Math.sqrt(i); j++){ if(i % j == 0){ continue label1; } } System.out.print(i+" "); } long end = System.currentTimeMillis(); System.out.println("\n"+(end - start)); } }
其耗费时间为:195ms