埃拉托色尼筛子筛选素数

  1 /********************************************************************
  2     created:    2013/10/22
  3     created:    22:10:2013   12:51
  4     file base:    埃拉托色尼筛子
  5     file ext:    cpp
  6     author:        Justme0 (http://blog.csdn.net/Justme0)
  7     
  8     purpose:    高效筛选素数
  9 *********************************************************************/
 10 #include <iostream>
 11 #include <vector>
 12 #include <cassert>
 13 using namespace std;
 14 
 15 /*
 16 ** initially all set to true
 17 */
 18 void initiate(vector<bool> &A) {
 19     assert(A.size() >= 3);
 20     for (unsigned i = 2; i < A.size(); ++i) {
 21         A[i] = true;
 22     }
 23 }
 24 
 25 /*
 26 ** the size of A is n+1
 27 ** Let A be an array of Boolean values, indexed by integers 2 to n
 28 */
 29 void sieveOfEratosthenes(vector<bool> &A) {
 30     assert(A.size() >= 3);
 31 
 32     initiate(A);
 33 
 34     int n = A.size() - 1;
 35     for (int i = 2; i * i <= n; ++i) {
 36         if (A[i]) {
 37             for (int j = i * i; j <= n; j += i) {
 38                 A[j] = false;
 39             }
 40         }
 41     }
 42 }
 43 
 44 void outputPrime(const vector<bool> &A) {
 45     int cnt = 1;
 46     for (unsigned i = 2; i < A.size(); ++i) {
 47         if (A[i]) {
 48             cout << cnt++ << '	' << i << endl;
 49         }
 50     }
 51 }
 52 
 53 int main(int argc, char **argv) {
 54     int n;
 55     while (cout << "请输入数字:
", cin >> n) {    
 56         vector<bool> A(1 + n);
 57         sieveOfEratosthenes(A);
 58         outputPrime(A);
 59     }
 60 
 61     system("pause");
 62     return 0;
 63 }
 64 
 65 /*
 66 
 67 #include <iostream>
 68 #include <algorithm>
 69 #include <cassert>
 70 using namespace std;
 71 
 72 const int LENGTH = 26;
 73 
 74 void getPrimeNum(int *a, int len) {
 75 assert(len >= 3 && "长度不足");
 76 
 77 a[0] = -1;
 78 a[1] = -1;
 79 
 80 // 1. 小于sqrt(n)即可
 81 for (int primeIndex = 2; primeIndex * primeIndex < len - 1; ++primeIndex) {
 82 while (-1 == a[primeIndex]) {
 83 ++primeIndex;
 84 if (primeIndex >= len) {
 85 return ;
 86 }
 87 }
 88 
 89 // 2. 从primeIndex^2开始
 90 for (int i = primeIndex * primeIndex; i < len; i += primeIndex) {
 91 a[i] = -1;
 92 }
 93 }
 94 }
 95 
 96 int main(int argc, char **argv) {
 97 int a[LENGTH];
 98 for (int i = 0; i < LENGTH; ++i) {
 99 a[i] = i;
100 }
101 
102 getPrimeNum(a, LENGTH);
103 
104 for (int i = 0, cnt = 1; i < LENGTH; ++i) {
105 if (a[i] != -1) {
106 cout << cnt++ << '	' << a[i] << endl;
107 }
108 }
109 
110 return 0;
111 }
112 
113 */

原文地址:https://www.cnblogs.com/jjtx/p/3382210.html