<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
# Sieve - 篩選算法
--------
#### 問題
素數是除了$$ 1 $$和它自身沒有其他數能夠整除的正整數,最小的素數是$$ 2 $$。而不符合該特性的正整數是合數,常見的素數有$$ 2, 3, 5, 7, 9, 11, 13, 17, 19, 23 \dots $$。素數是數論學科中的基礎概念,關于素數的最為著名的問題就是哥德巴赫猜想。
判斷$$ [1 \dots n) $$中哪些是素數,哪些是合數。
#### 解法
按照素數的定理,判斷一個正整數$$ x $$是否為素數,需要遍歷$$ [1 \dots x] $$中所有數字$$ i $$是否能被$$ x $$整除,即$$ x % i = 0 $$。判斷一個數字的時間復雜度為$$ O(n) $$,判斷$$ n $$個數字的時間復雜度為$$ O(n ^ 2) $$。埃拉托斯特尼篩選法(Eratosthenes Sieve)可以更快的完成所有判斷。
設置數組$$ s = [1 \dots n) $$,$$ s[i] $$表示數字$$ i $$是否為素數。初始時顯然有$$ s[1] = false $$。
$$ (1) $$ 以$$ 2 $$為篩子,$$ s[2] = true, s[2 \times 2] = false, s[2 \times 3] = false \dots $$,除了$$ 2 $$本身,所有$$ 2 $$的倍數都不是素數;
$$ (2) $$ 以$$ 3 $$為篩子,$$ s[3] = true, s[3 \times 2] = false, s[3 \times 3] = false \dots $$,除了$$ 3 $$本身,所有$$ 3 $$的倍數都不是素數;
$$ (3) $$ 以$$ 5 $$為篩子,$$ s[5] = true, s[5 \times 2] = false, s[5 \times 3] = false \dots $$,除了$$ 5 $$本身,所有$$ 5 $$的倍數都不是素數;
$$
\cdots
$$
因為顯然偶數中除了$$ 2 $$都是合數,可以跳過所有偶數只考察奇數。
--------
#### 源碼
[Sieve.h](https://github.com/linrongbin16/Way-to-Algorithm/blob/master/src/NumberTheory/Sieve.h)
[Sieve.cpp](https://github.com/linrongbin16/Way-to-Algorithm/blob/master/src/NumberTheory/Sieve.cpp)
#### 測試
[SieveTest.cpp](https://github.com/linrongbin16/Way-to-Algorithm/blob/master/src/NumberTheory/SieveTest.cpp)
- Content 目錄
- Preface 前言
- Chapter-1 Sort 第1章 排序
- InsertSort 插入排序
- BubbleSort 冒泡排序
- QuickSort 快速排序
- MergeSort 歸并排序
- Chapter-2 Search 第2章 搜索
- BinarySearch 二分查找法(折半查找法)
- BruteForce 暴力枚舉
- Recursion 遞歸
- BreadthFirstSearch 廣度優先搜索
- BidirectionalBreadthSearch 雙向廣度搜索
- AStarSearch A*搜索
- DancingLink 舞蹈鏈
- Chapter-3 DataStructure 第3章 數據結構
- DisjointSet 并查集
- PrefixTree(TrieTree) 前綴樹
- LeftistTree(LeftistHeap) 左偏樹(左偏堆)
- SegmentTree 線段樹
- FenwickTree(BinaryIndexedTree) 樹狀數組
- BinarySearchTree 二叉查找樹
- AVLTree AVL平衡樹
- RedBlackTree 紅黑樹
- Chapter-4 DynamicProgramming 第4章 動態規劃
- Chapter-5 GraphTheory 第5章 圖論
- Chapter-6 Calculation 第6章 計算
- LargeNumber 大數字
- Exponentiation 求冪運算
- Chapter-7 CombinatorialMathematics 第7章 組合數學
- FullPermutation 全排列
- UniqueFullPermutation 唯一的全排列
- Combination 組合
- DuplicableCombination (元素)可重復的組合
- Subset 子集
- UniqueSubset 唯一的子集
- Permutation 排列
- PermutationGroup 置換群
- Catalan 卡特蘭數
- Chapter-8 NumberTheory 第8章 數論
- Sieve 篩選算法
- Euclid 歐幾里得
- EuclidExtension 歐幾里得擴展
- ModularLinearEquation 模線性方程
- ChineseRemainerTheorem 中國剩余定理
- ModularExponentiation 模冪運算
- Chapter-9 LinearAlgebra 第9章 線性代數
- Chapter-10 AnalyticGeometry 第10章 解析幾何
- Chapter-11 TextMatch 第11章 文本匹配
- SimpleMatch 簡單匹配
- AhoCorasickAutomata AC自動機
- KnuthMorrisPratt KMP匹配算法
- RabinKarp RabinKarp算法
- BoyerMoore BoyerMoore算法
- Chapter-12 GameTheory 第12章 博弈論
- BashGame 巴什博弈
- WythoffGame 威佐夫博弈
- NimGame 尼姆博弈