-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenumerate_prime_number.h
More file actions
39 lines (33 loc) · 859 Bytes
/
Copy pathenumerate_prime_number.h
File metadata and controls
39 lines (33 loc) · 859 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#ifndef CPP_ALGORITHM_ENUMERATE_PRIME_NUMBER_H
#define CPP_ALGORITHM_ENUMERATE_PRIME_NUMBER_H
#include <deque>
#include <vector>
namespace EnumeratePrime
{
/**
* \brief Enumerate prime numbers in the range.
* \param n upper bound
* \return prime numbers
*/
std::vector<int> GeneratePrimes(int n);
}
// ----------------------------------------------------------------------------
inline std::vector<int> EnumeratePrime::GeneratePrimes(const int n)
{
std::vector<int> primes;
std::deque<bool> is_prime(n + 1, true);
is_prime[0] = is_prime[1] = false;
for (int p = 2; p <= n; ++p)
{
if (is_prime[p])
{
primes.push_back(p);
for (int i = p * 2; i <= n; i += p)
{
is_prime[i] = false;
}
}
}
return primes;
}
#endif