Skip to content

Instantly share code, notes, and snippets.

@rongjiecomputer
Created April 5, 2017 00:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rongjiecomputer/d52f34d27a21b8c9c9e82ca85b806640 to your computer and use it in GitHub Desktop.
Save rongjiecomputer/d52f34d27a21b8c9c9e82ca85b806640 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes with C++ constexpr
#include <stdio.h>
template <size_t N>
struct PrimeTable {
constexpr PrimeTable() : sieve() {
sieve[0] = sieve[1] = false;
for (size_t i = 2; i < N; i++) sieve[i] = true;
for (size_t i = 2; i < N; i++) {
if (sieve[i])
for (size_t j = i*i; j < N; j += i) sieve[j] = false;
}
}
bool sieve[N];
};
int main() {
constexpr auto table = PrimeTable<100000>();
for (int i = 0; i < 20; i++) {
printf("isPrime(%d): %d\n", i, table.sieve[i]);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment