I am using sieve method to print all the prime numbers to a file. My code is as below:
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE* file = fopen("primeList.txt","w+");
bool* x;
// long upLimit=100;
long upLimit=2000000000;
x=(bool*) calloc(1,upLimit);
long i=upLimit;
while(i--){
*(x+i)=true;
}
*(x+1)=false;
*(x+2)=true;
*(x+3)=true;
int cnum=2;
int count=0;
while(cnum<upLimit){
if(*(x+cnum)){
fprintf(file, "%d\n",cnum);
count++;
int compNum=cnum*2;
while(compNum<upLimit){
*(x+compNum)=false;
compNum+=cnum;
}
}
cnum+=1;
}
fprintf(file, "Count is : %d\n", count);
fflush(file);
fclose(file);
return 0;
}
The last few lines from outfile is as below:
I am expecting count of primes to be the last line. Please help with the issue. Thanks in advance.
