java Eratostenes的筛子(素数)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java Eratostenes的筛子(素数)相关的知识,希望对你有一定的参考价值。

/*
*This example implements a method that returns
*a list of the prime numbers up to a number given
*/

import java.util.ArrayList;
import java.util.Arrays;

public class SieveEratostenes {

	public static void main(String[] args) {
		int primesUntil = 100;
		ArrayList<Integer> result = sieveOfEratostenes(primesUntil);
		System.out.println("The primes from 2 to "+primesUntil+" are: "+result.toString());
	}	
	
	//Parameter: max value for which we will check if its part of the list of primes
	static ArrayList<Integer> sieveOfEratostenes(int max){
		int[] init = new int[max];
		//Build array with values from 2 to max.
		for(int i = 0, value = 2; i < init.length; i++, value++){
			init[i] = value;
		}
		ArrayList<Integer> result = new ArrayList<Integer>();
		boolean[] crossedOut = new boolean[max];
		int index = 0;
		int pivot = init[index];
		crossedOut[index] = true;
		while(!allCrossedOut(crossedOut)){
			crossedOut[index] = true;
			//Cross out the values that are divisible by pivot
			for(int i = index + 1; i < init.length; i++){
				int evaluatedElem = init[i];
				if(evaluatedElem % pivot == 0){//Cross it out
					crossedOut[i] = true;
				}
			}
			//Find new pivot with the next value in the 
			//list that has not been crossed out yet
			for(int i = index+1; i < init.length; i++){
				if(crossedOut[i] == false){
					result.add(pivot);
					pivot = init[i];
					index = i;
					break;
				}
			}
		}
		
		return result;
	}
	//This methods checks if all values have been marked as true in an array
	static boolean allCrossedOut(boolean[] crossedOut){
		for(boolean b : crossedOut){
			if (b == false){
				return false;
			}
		}  
		return true;
	}

}

以上是关于java Eratostenes的筛子(素数)的主要内容,如果未能解决你的问题,请参考以下文章

使用筛子找到小于 LONG 数的素数

HDU 4548 美素数 素数题解

算法杂谈埃氏素数筛

三 数论的编程实验

找出所有低于 40 亿的素数的最快方法

Erlang中Eratosthenes的筛子最高素因子