标签:
(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
标签:
原文地址:http://www.cnblogs.com/mengrennwpu/p/4768835.html