#include<iostream>
using namespace std;
template<int N> class Prime
{ // generate N prime numbers at compile time
public:
unsigned int arr[N]{};
constexpr Prime() {
int k=0;
for(unsigned int i=2; k<N; i++) {
bool isPrime = true;
for(int j=0; j<k; j++) {
if(arr[j] > i/2) break;
if(i % arr[j] == 0) {
isPrime = false;
break;
}
}
if(isPrime) arr[k++] = i;
}
}
};
int main()
{
Prime<50000> prime; // if 50000->5000, ok
for(auto& a : prime.arr) cout << a << ' ';
}
G++ fails to compile this code. It spends ages trying to compile, uses lots of memory, and finally just crashes.
If I make the number 50000 smaller, or get rid of constexpr
, it compiles. But I want to use bigger arrays to save time.
Any ideas will be appreciated.