Skip to content

Instantly share code, notes, and snippets.

@pocarist
Created September 15, 2015 03:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pocarist/4e42bf458211bd158602 to your computer and use it in GitHub Desktop.
Save pocarist/4e42bf458211bd158602 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes
#include <vector>
#include <cmath>
using namespace std;
vector<int> primes(int n)
{
vector<bool> table(n + 1, true);
table[0] = table[1] = false;
int mid = (int)floor(sqrt(n));
for (int i = 2; i <= mid; i++) {
if (table[i]) {
for (int j = i+i; j <= n; j += i)
table[j] = false;
}
}
vector<int> ans;
for (int i = 2; i <= n; i++)
if (table[i])
ans.push_back(i);
return ans;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment