Skip to content

Instantly share code, notes, and snippets.

@philopaterwaheed
Created January 31, 2024 08:43
Show Gist options
  • Save philopaterwaheed/932993bc83511a709f43d89e8993c48a to your computer and use it in GitHub Desktop.
Save philopaterwaheed/932993bc83511a709f43d89e8993c48a to your computer and use it in GitHub Desktop.
the best algorithem to get all prime nubers under an int
std :: vector primes_under (int n ) {
std::vector<bool> isPrime(n + 1, true);
std :: vector <int> primes ;
for (int p =2 ; p * p< (n) ; p ++ )
if (isPrime[p]) {
// If p is prime, mark all multiples of p as non-prime
for (int i = p * p; i <= n; i += p) {
isPrime[i] = false;
}
}
for (int p = 2; p <= n; ++p) {
if (isPrime[p]) {
primes.push_back(p);
}
}
return primes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment