Sieve of Eratosthenes(埃拉托斯特尼素数筛选法)--java实现

来源:互联网 发布:集搜客网页抓取软件 编辑:程序博客网 时间:2024/05/24 07:19

埃拉托色尼筛选法

埃拉托色尼选筛法(the Sieve of Eratosthenes)简称埃氏筛法,是古希腊数学家埃拉托色尼(Eratosthenes 274B.C.~194B.C.)提出的一种筛选法。 是针对自然数列中的自然数而实施的,用于求一定范围内的质数。

步骤

(1)先把1删除(现今数学界1既不是质数也不是合数)
(2)读取队列中当前最小的数2,然后把2的倍数删去
(3)读取队列中当前最小的数3,然后把3的倍数删去
(4)读取队列中当前最小的数5,然后把5的倍数删去

(5)如上所述直到需求的范围内所有的数均删除或读取

示例

Apply sieve of Eratosthenes to find all primes in range 2..100.

Initial grid

Sieve of Eratosthenes example, initial grid

2 is prime, mark all multiples of 2, starting from 4

Sieve of Eratosthenes example, 2 is prime, mark all multiples of 2

3 is prime, mark all multiples of 3, starting from 9

Sieve of Eratosthenes example, 3 is prime, mark all multiples of 3, starting from 9

5 is prime, mark all multiples of 5, starting from 25

Sieve of Eratosthenes example, 5 is prime, mark all multiples of 5, starting from 25

7 is prime, mark all multiples of 7, starting from 49

Sieve of Eratosthenes example, 7 is prime, mark all multiples of 7, starting from 49

112 is more, than 100, all unmarked numbers are primes

Sieve of Eratosthenes example, 11^2 is more, than 100, all unmarked numbers are primes

Final result

Sieve of Eratosthenes example, final result

代码

public class Prime_Sieve {private boolean[] sieveOfEratothenes(int max) {boolean[] flags = new boolean[max + 1];// int count = 0;for (int i = 2; i < flags.length; i++) {flags[i] = true;}int prime = 2;while (prime <= max) {// 划掉余下prime倍数的数字crossOff(flags, prime);// 找出下一个为true的值prime = getNextPrime(flags, prime);if (prime >= flags.length) {break;}}return flags;}private void crossOff(boolean[] flags, int prime) {// 划掉余下为prime倍数的数字// 我们可以从prime*prime开始// 因为如果k*prime且k<prime,这个值早就在迭代之前就被划掉了for (int i = prime * prime; i < flags.length; i = i + prime) {flags[i] = false;}}private int getNextPrime(boolean[] flags, int prime) {int next = prime + 1;while (next < flags.length && flags[next] == false) {next++;}return next;}public static void main(String[] args) {Prime_Sieve myPrime_Sieve = new Prime_Sieve();boolean[] mySieveArray = myPrime_Sieve.sieveOfEratothenes(16);for (int i = 0; i <= 16; i++) {System.out.println(i + " is prime: " + mySieveArray[i]);}}}

优化

当然上面的代码中,还有一些地方可以优化,比如只将奇数放入数组所需空间即可减半。
1 0