首页 > 其他 > 详细

普通方法求素数与筛法求素数比較

时间:2017-06-19 15:05:04      阅读:273      评论:0      收藏:0      [点我收藏+]
普通方法求素数与筛法求素数比較
20150806

package day06;

/*
 * 普通方法求素数与筛法求素数比較
 */
import java.util.*;

public class TestSushu {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		System.out.print("查找范围2~");
		int n = scan.nextInt();
		
		long s1=System.currentTimeMillis();
		//1--普通方法求素数
		int count1 = 0;
		for(int i=2,j=0;i<=n;i++){
			int temp=(int)(Math.sqrt(i));
			for(j=2;j<=temp;j++){
				if(i%j==0){
					break;
				}
			}
			if(j>temp){
				//System.out.print(i+"\t");
				count1 ++;
				if(count1%15==0){
					//System.out.println();
				}
			}			
		}
		System.out.println("\n"+"2~"+n+"共同拥有"+count1+"个素数");
		long e1=System.currentTimeMillis();
		System.out.println("time1="+(e1-s1));
		System.out.println("******************");
		
		long s2=System.currentTimeMillis();
		//2--筛法求素数
		boolean[] b = new boolean[n+1];
		b[0]=b[1]=true;
		for(int i=2;i<b.length;i++){
			if(!b[i]){
				for(int j=i*2;j<b.length;j+=i){
					b[j]=true;
				}
			}
		}
		int count2 = 0;
		for(int i=2;i<b.length;i++){
			if(!b[i]){
				//System.out.print(i+"\t");
				count2++;
				if(count2%15==0){
					//System.out.println();
				}
			}
		}
		System.out.println("\n"+"2~"+n+"共同拥有"+count2+"个素数");
		long e2=System.currentTimeMillis();
		System.out.println("time2="+(e2-s2));
		
	}

}


筛法求素数原理:

技术分享


总结:筛法求素数速度更快,尤其是数据比較大的时候


普通方法求素数与筛法求素数比較

原文:http://www.cnblogs.com/tlnshuju/p/7048585.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!