Created
September 9, 2014 13:04
-
-
Save chengluyu/a831b0c498ac578805db to your computer and use it in GitHub Desktop.
Prime Numbers Generator in Liner Time
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
const int MAX = 2000000; | |
bool is_prime[MAX + 1] = { 0 }; | |
std::vector<int> primes; | |
int main() { | |
is_prime[2] = true; | |
for (int i = 2; i <= MAX; i++) { | |
if (!is_prime[i]) | |
primes.push_back(i); | |
for (size_t j = 0; j < primes.size(); j++) { | |
if ((long long)primes[j] * i > MAX) | |
break; | |
is_prime[primes[j] * i] = true; | |
if (i % primes[j] == 0) | |
break; | |
} | |
} | |
std::cout << primes.size() << std::endl; | |
} | |
/* | |
# Test result | |
Cheng@CHENG-PC ~/Desktop | |
$ time a | |
227431 | |
real 0m0.187s | |
user 0m0.015s | |
sys 0m0.062s | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment