2-100000之间的质数个数,并进行优化
这是根据题意直接写出的代码片段:
//获取当前时间距离的毫秒数;
long start=System.currentTimeMillis();
//计算输出个数;
int count=0;
//标识是否被除尽,一旦除尽,改为false;
boolean isFlag=true;
//遍历10000以内的自然数
for(int a=2;a<=100000;a++){
//遍历范围为(2-(100000-1))内的数
for(int other=2;other<a;other++){
//取余为0;
if(a%other==0){
isFlag=false;
}
}
if(isFlag==true){
count++;
}
isFlag=true;
}
// 获取当时时间距离的毫秒数;
long end=System.currentTimeMillis();
System.out.println("执行时间为"+(end-start));
下面开始第一步的优化,利用break;
//获取当前时间距离的毫秒数;
long start=System.currentTimeMillis();
//标识是否被除尽,一旦除尽,改为false;
boolean isFlag=true;
//计算输出个数;
int count=0;
//遍历10000以内的自然数
for(int a=2;a<=100000;a++){
for(int other=2;other<a;other++){
//取余为0;
if(a%other==0){
isFlag=false;
//优化一:只对本身非质数的自然数有效
break;
}
}
if(isFlag==true){
count++;
}
isFlag=true;
}
// 获取当时时间距离的毫秒数;
long end=System.currentTimeMillis();
System.out.println("执行时间为"+(end-start));
利用break执行的时间:
2.在break的基础上对内部循环的j进行开方运算
//获取当前时间距离的毫秒数;
long start=System.currentTimeMillis();
//标识是否被除尽,一旦除尽,改为false;
boolean isFlag=true;
//计算输出个数;
int count=0;
//遍历10000以内的自然数
for(int a=2;a<=100000;a++){
//优化二:对质数本身是自然数有效的开方运算 Math.sqrt(a)
for(int other=2;other<=Math.sqrt(i);other++){
//取余为0;
if(a%other==0){
isFlag=false;
//优化一:只对本身非质数的自然数有效
break;
}
}
if(isFlag==true){
count++;
}
isFlag=true;
}
// 获取当时时间距离的毫秒数;
long end=System.currentTimeMillis();
System.out.println("执行时间为"+(end-start));
进行开方运算的执行时间:
经过两次对质数和非质数的部分进行优化,可以很明显的看出运行时间不断缩短。break可以看做是一个常用的优化方式,而开方的这种形式要跟根据具体的问题在进行改变。