埃拉托斯特尼筛法

埃拉托斯特尼筛法希腊语κόσκινον Ἐρατοσθένους,英语:sieve of Eratosthenes),简称埃氏筛,也称素数筛,是简单且历史悠久的筛法,用来找出一定范围内所有素数

原理是从2开始,将每个素数的各倍数标记成合数。一个素数的各个倍数,是一个差为此素数本身的等差数列。此为这个筛法和试除法不同的关键之处,后者是以素数来测试能否整除每个待测数。

素数筛是列出所有小素数的有效方法,得名于古希腊数学家埃拉托塞尼,并且描述在另一位古希腊数学家尼科马库斯所著的《算术入门》中。[1]

算式

定出要筛数值的范围n,找出 以内的素数 。先用2去筛,把2留下,把2的倍数剔除掉;再用下个素数3筛,把3留下,把3的倍数剔除掉;接下去用下个素数5筛,把5留下,把5的倍数剔除掉,直至够为止。

步骤

详细列出算法如下:

  1. 列出2以后所有数:
    • 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
  2. 标记第一个质数2:
    • 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
  3. 用红色标记2的倍数:
    • 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
  4. 如果最大数不大于最后一个标出的素数的平方,那么剩下的所有的数都是质数,否则回到第二步。

  1. 本例中,25大于2的平方,返回第二步:
  2. 2之后第一个质数是3,用蓝色标记3的倍数:
    • 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
  1. 得到的质数是2,3。
  2. 25仍大于3的平方,再次返回第二步:
  3. 3之后第一个质数是5,用绿色标记5的倍数:
    • 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
  4. 得到的质数是2,3,5。
  5. 25是5的平方,筛选完毕。

结论:去掉红色及绿色的数,25内的质数是2,3,5,7,11,13,17,19,23。

算法

素数筛可用以下伪代码表示:

輸入:整數n > 1
 
設A為布爾值陣列,指標是2至n的整數,
初始時全部設成true。
 
 for i = 2, 3, 4, ..., 不超過 if A[i]為truefor j = i2, i2+i, i2+2i, i2+3i, ..., 不超過nA[j] := false
 
輸出:使A[i]為true的所有i

以上算法可以得到小于等于n的所有素数,它的复杂度是O(n log log n)

程式码

Python 3.6-3.10

def eratosthenes(n):
    is_prime = [True] * (n + 1)
    for i in range(2, int(n ** 0.5) + 1):
        if is_prime[i]:
            for j in range(i * i, n + 1, i):
                is_prime[j] = False
    return [x for x in range(2, n + 1) if is_prime[x]]
print(eratosthenes(120))

C语言

int prime[100005];
bool is_prime[1000005];

int eratosthenes(int n) {
    int p = 0;
    for (int i = 0; i <= n; i++) {
        is_prime[i] = true;
    }
    is_prime[0] = is_prime[1] = 0;
    for (int i = 2; i <= n; i++) {
        if (is_prime[i]) {
            prime[p++] = i;
            if (1ll * i * i <= n) {
                for (int j = i * i; j <= n; j += i) {
                    is_prime[j] = 0;
                }
            }
        }
    }
    return p;
}

C语言新版

#include <stdio.h>
#include <stdlib.h>

/* N: positive integer
   verbose: 1 -- print all prime numbers < N, 0 -- no print
   return total number of prime numbers < N. 
   return -1 when there is not enough memory.
*/
int eratosthenesSieve(unsigned long long int N, int verbose) {
  // prime numbers are positive, better to use largest unsiged integer
  unsigned long long int i, j, total; // total: number of prime numbers < N
  _Bool *a = malloc(sizeof(_Bool) * N);

  if (a == NULL) {
    printf("No enough memory.\n");
    return -1;
  }
  
  /* a[i] equals 1: i is prime number.
     a[i] equals 0: i is not prime number.
     From beginning, set i as prime number. Later filter out non-prime numbers
  */
  for (i = 2; i < N; i++) {
    a[i] = 1; 
  }

  // mark multiples(<N) of i as non-prime numbers
  for (i = 2; i < N; i++) {
    if (a[i]) { // a[i] is prime number at this point
      for (j = i; j < (N / i) + 1; j++) {
	/* mark all multiple of 2 * 2, 2 * 3, as non-prime numbers;
	   do the same for 3,4,5,... 2*3 is filter out when i is 2
	   so when i is 3, we only start at 3 * 3
	*/
	a[i * j] = 0;
      }
    }
  }

  // count total. print prime numbers < N if needed.
  total = 0;
  for (i = 2; i < N; i++) {
    if (a[i]) { // i is prime number
      if (verbose) {
	printf("%llu\n", i);
      }
      total += 1;
    }
  }

  return total;
}

int main() {
  unsigned long long int a1 = 0, a2 = 0, N = 10000000;
  
  a1 = eratosthenesSieve(N, 1); // print the prime numbers
  printf("Total of prime numbers less than %llu is : %llu\n", N, a1);
  
  a2 = eratosthenesSieve(N, 0); // not print the prime numbers
  printf("Total of prime numbers less than %llu is : %llu\n", N, a2);
  
  return 0;
}

C++

#include <vector>

auto eratosthenes(int upperbound) {
  std::vector<bool> flag(upperbound + 1, true);
  flag[0] = flag[1] = false; //exclude 0 and 1
  for (int i = 2; i * i <= upperbound; ++i) {
    if (flag[i]) {
      for (int j = i * i; j <= upperbound; j += i)
        flag[j] = false;
    }
  }	
  return flag;
}

R

eratosthenes <- function(n) {
  if (n == 1) return(NULL)
  if (n == 2 | n == 3) return(2:n)
  numbers <- 2:n
  primes <- rep(TRUE, n-1)
  for (i in 2:floor(sqrt(n))) {
    if (primes[i-1]) {
      for (j in seq(i * i, n, i))
        primes[j-1] <- FALSE
    }
  }
  return(numbers[primes])
}

JavaScript

const countPrimes = function (n) {
  const isPrime = new Array(n).fill(true);

  for (let i = 2; i <= Math.sqrt(n); i++) {
    if (isPrime[i]) {
      for (let j = i * i; j <= n; j += i) {
        isPrime[j] = false;
      }
    }
  }

  let count = 0;
  for (let i = 2; i < n; i++) {
    if (isPrime[i]) {
      count++;
    }
  }

  return count;
};

参见

参考文献

  1. ^ Nicomachus, Introduction to Arithmetic, I, 13. [1]
  • Κοσκινον Ερατοσθενους or, The Sieve of Eratosthenes. Being an Account of His Method of Finding All the Prime Numbers, by the Rev. Samuel Horsley, F. R. S., Philosophical Transactions (1683-1775), Vol. 62. (1772), pp. 327-347.

拓展阅读