I read up on the sieve of Eratosthenes while solving a question on Project Euler. I'm sure you guys know which question im talking about. So here's the thing. My code manages to show all the primes under 1 million correctly. However when i try the same implementation for 2 million it's giving me a segmentation fault... I have a certain idea of why the error is coming but don't know how to correct it... Here's the code for primes under 1 million.
#include<stdio.h>
int main(void)
{
int i,k=2;
int j;
int n=1000000;
int prime[2000000]={};
for(i=0;i<n;i++) // initializes the prime number array
{
prime[i]=i;
}
for(i=2;i<n;i++) // Implementation of the Sieve
{
if(prime[i]!=0)
{
for(j=2;j<n;j++)
{
{
prime[j*prime[i]]=0;
if(prime[i]*j>n)
break;
}
}
}
}
for(i=0;i<n;i++) // Prints the prime numbers
if(prime[i]!=0)
{
printf("%d\n"prime[i]);
}
return(0);
}
}
int n=1000000;
toint n=2000000;
– Burlingameprime[j*prime[i]]=0
. – Headstockint
. Int is not guaranteed to be any particular size, other than 16 bit. As a style issue I would recommendlong
for numbers above 32k. – Subrogatesize_t
– Burlingame