Skip to content

Instantly share code, notes, and snippets.

@chengluyu
Created September 9, 2014 13:04
Show Gist options
  • Save chengluyu/a831b0c498ac578805db to your computer and use it in GitHub Desktop.
Save chengluyu/a831b0c498ac578805db to your computer and use it in GitHub Desktop.
Prime Numbers Generator in Liner Time
#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