I'm making the sieve of erasthostenes in c. I have programmed it in other languages before but I never encountered this problem. Here's my algorithm:
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
#include <time.h>
#include <limits.h>
int main(){
clock_t t;
t = clock();
int n = 1299710;
bool pPrimes[n];
for(int i = 0; i<n; i++){
pPrimes[i] = true;
}
pPrimes[0] = false;
pPrimes[1] = false;
for(int i = 2; i<sqrt(n); i++){
if(pPrimes[i]){
for(int x = i*i; x<n; x+=i){
pPrimes[x] = false;
}
}
}
for(int i = 2; i<n; i++){
if (pPrimes[i]){
printf("%d\n", i);
}
}
t = clock() - t;
double time_taken = ((double)t)/CLOCKS_PER_SEC;
printf("%f", time_taken);
return 0;
}
It's when I declare pPrimes that n can't be large enough. A million or so works but not more. Is there anyway of fixing this?
I tried debugging but I only get this error message:
line 1: 4320 Segmentation fault: 11
Some issues:
Out of local space
OP reports with large
n, there is trouble. Better to allocate withmalloc().boolis not certainly the narrowest type - useunsigned char. Better to allocate with an unsigned size such asunsignedorsize_t.Off by one
I would expect
int n = 1299710;to imply finding all the primes up to and includingn.Referencing this pseudocode, edge tests are off by one.
Do not trust a raw
sqrt()for an integer problem. When the expected result is x.00000..., that function may return x_minus_1.99999....