This shows you the differences between two versions of the page.
| Both sides previous revision Previous revision Next revision | Previous revision | ||
|
algorithms_primes [2018/08/09 09:29] jguerin Added cs1 machine, Python/C++ flag info. |
— (current) | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| - | ====== Algorithms: Prime Numbers ====== | ||
| - | |||
| - | |||
| - | ===== Prime Sieves ===== | ||
| - | Prime sieves are common devices for generating prime numbers in a given range. These lists can be used for quick verification of relatively small prime numbers (typically ranging up to 10< | ||
| - | |||
| - | == Etymology == | ||
| - | A sieve((Pronounced like " | ||
| - | |||
| - | ==== Sieve of Eratosthenes ==== | ||
| - | <file python sieve.py> | ||
| - | from math import * | ||
| - | |||
| - | def sieve(n): | ||
| - | primes = [True] * (n+1) # generate a list of primes | ||
| - | primes[0] = primes[1] = False | ||
| - | for i in range(2, int(sqrt(n))+1): | ||
| - | for j in range(i**2, n+1, i): | ||
| - | primes[j] = False | ||
| - | return [i for i in range(len(primes)) if primes[i]] # generate primes from True values | ||
| - | |||
| - | primes = sieve(1000000) | ||
| - | </ | ||
| - | |||
| - | <file c++ sieve.cpp> | ||
| - | #include < | ||
| - | #include < | ||
| - | #include < | ||
| - | #include < | ||
| - | |||
| - | using namespace std; | ||
| - | |||
| - | const int MAX_PRIMES=10000000; | ||
| - | |||
| - | vector< | ||
| - | bitset< | ||
| - | nums.set(); | ||
| - | nums[0] = nums[1] = false; | ||
| - | for(int i=2; i< | ||
| - | for(int j=i*i; j<n+2; j+=i) | ||
| - | nums[j] = false; | ||
| - | |||
| - | vector< | ||
| - | for(int i=0; i< | ||
| - | if(nums[i] == true) | ||
| - | primes.push_back(i); | ||
| - | |||
| - | return primes; | ||
| - | } | ||
| - | |||
| - | int main() { | ||
| - | vector< | ||
| - | |||
| - | return 0; | ||
| - | } | ||
| - | </ | ||
| - | |||
| - | === Design Principles === | ||
| - | Operation Sieve of Eratosthenes is quite simple. The sieve starts by assuming all numbers in a given range (2..n) are prime ('' | ||
| - | |||
| - | === Implementation Notes === | ||
| - | A C++ [[cpp_std_bitset|bitset]](([[http:// | ||
| - | |||
| - | |||
| - | === Analysis === | ||
| - | The Sieve of Eratosthenes is not the fastest prime sieve available, but it is quick to code, easy to understand and modify, and sufficiently fast for some practical applications. | ||
| - | |||
| - | **Time Complexity: | ||
| - | **Space Complexity: | ||
| - | |||
| - | === Benchmarks === | ||
| - | The Python3 implementation should work reliably for primes up to 10< | ||
| - | |||
| - | ^ %%n%% ^ Python3((Python 3.5.2)) | ||
| - | | 10< | ||
| - | | 10< | ||
| - | | 10< | ||
| - | |||
| - | Redo benchmarks on desktop. | ||
| - | |||
| - | === Source === | ||
| - | Implementations are from the pseudocode provided in the Wikipedia article on the [[https:// | ||