算法优化-以输出质数为例

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可以看做是一个常用的优化方式,而开方的这种形式要跟根据具体的问题在进行改变。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值