I have been trying to execute this program on my MinGW, through Code::Blocks:
#include <string.h>
#include <math.h>
#include <stdio.h>
#define N 100
int p[N];
int pr[N];
int cnt;
void sieve()
{
int i,j;
for(i=0;i<N;i++) pr[i]=1;
pr[0]=pr[1]=0;
for(i=2;i<N;i++)
if(pr[i])
{
p[cnt]=i; cnt++;
for(j=i+i;j<=N;j+=i) pr[j]=0;
}
}
int main(){
sieve();
int i;
for(i=0;i<cnt;i++)
printf("%d ",p[i]);
puts("");
printf("Total number of prime numbers : %d",cnt);
return 0;
}
On my system the output is:
7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Total number of prime numbers : 22
Which is completely insane, since I am completely sure about the implementation of my algorithm.
So I decided to try it in Ideone where it gives correct output. Can anybody point out the reason ?
I changed it to N, but the output doesn’t change.
There are two important bugs in your code.
One is that your p array is too small, so you are writing off the end of it. This is undefined behaviour, though on the platforms you are using it overwrites the start of the pr array. This has no effect on the output, since the location you are overwriting is before the location you are testing in the sieve.
The other is that you are also writing off the end of your
prarray:This loops sets
pr[N]to zero, which is off the end ofpr. In MinGW this is wherecntis stored, so each timeidividesN,cntis set to zero. AsNis 100, this happens fori==2andi==5, so you lose the primes before five from your result. IdeOne seems to putcntsomewhere else in relation topr, so it does not get overwritten. This is why you get different output with the different compilers.Change the size of the array p to N, or use only one array for both sieve and output, and change
<=in line 18 to<so you don’t write off the end of it.