【java学习】快速求素数的方法

学习的一种快速求素数的方法,原帖:http://blog.csdn.net/lichengiggs/article/details/722842

主要思路:给定范围大小size:

  1. primeNum存储0~size个数,初始值都为0
  2. 求出2~sqrt(size)范围内的所有素数,存入checker中
  3. 求出5~size范围内所有满足6n±1的数i,令primeNum[i]=1作为满足条件的标记
  4. 素数判断:对于sqrt(size)+1~size范围中的数j,并且标记为1,如果能被checker中的数整除,则令primeNum[j]=0,即不是素数
  5. 上述四步进行完后,输出primeNum[i]=1对应的下标i,即为0~size中的素数
(p.s:除了用数组标记方法外也可以使用容器,但是学渣表示不知道哪个效率好-_-)

代码:
public class Prime {
	private final int MAX_SIZE = 100; 
	private int[] primeNum;
	private int[] checker;
	private int checker_count;
	private int size;
	
	Prime(){
		this.size = 0;
		this.primeNum = new int[MAX_SIZE];
		this.checker = new int[2];
		this.checker[0] = 2;
		this.checker[1] = 3;
		this.checker_count = 2;
	}
	
	Prime(int size){
		this.size = size;
		this.primeNum = new int[size];
		this.checker = new int[(int)Math.sqrt(size)];
		this.checker[0] = 2;
		this.checker[1] = 3;
		this.checker_count = 2;
	}
	
	public boolean isPrime(int num){
		for (int i = 2; i < num; i++)
			if (num % i == 0)
				return false;
		return true;
	}
	/*prime num between 5~sqrt(size)*/
	public void pickChecker(){
		for(int i = 5; i < (int)Math.sqrt(this.size); i++)
			if (isPrime(i))
				this.checker[this.checker_count++] = i;			
	}
	/*6n+1 or 6n-1*/
	public void pickChosenNum(){
		for (int i = 5; i < this.size; i++)
			if ((i + 1) % 6 == 0 || (i - 1) % 6 == 0)
				this.primeNum[i] = 1;
				
		this.primeNum[2] = this.primeNum[3] = 1;
	}
	
	public void divideByChecker(){
		for (int i = (int)Math.sqrt(this.size)+1; i < this.size; i++)
			for (int j = 0; j < this.checker_count; j++){
				if (this.primeNum[i] != 0 && ((i % this.checker[j]) == 0))
					this.primeNum[i] = 0;		
			}
	}
	
	public void printPrimeNum(){
		int count = 0;
		for (int i = 2; i < this.size; i++)
			if (this.primeNum[i] == 1){
				count++;
				System.out.println(i);
			}
		System.out.println("count = "+count);		
	}
	public void findPrimeNum(){
		pickChecker();
		pickChosenNum();
		divideByChecker();
		printPrimeNum();
	}
	
	public static void main(String[] args){
		Prime prime = new Prime(100);
		prime.findPrimeNum();
	}
}


你可能感兴趣的:(【java学习】快速求素数的方法)