This code is for finding prime with the help of Sieve of Eratosthenes algorithm.
I tried to manage memory for the program so instead of declaring large element arry
i used calloc function.
But when i input more than 200 The Output screen doesn't show anything but says that the program executed in 3.XXX something s
and returned to -XYZCGG address.
What's the problem with the calloc?
Please help me to manage memory for the program in smart way and make the code more fast and optimized.
Any suggestions welcome :-)
Thanks.
#include<iostream>
#include<stdlib.h>
using namespace std;
int N=0;
char* ptr;
void gen_sieve_primes(void)
{
for (int p=2; p<N; p++)
{
if(*(ptr+p) == '0')
*(ptr+p) = 'p';
int c=2;
int mul = p * c;
for(mul=p*c; mul < N;c++)
{
*(ptr+mul) = 'c';
// c++;
mul = p*c;
}
}
}
void print_all_primes()
{
int c = 0;
for(int i=0; i<N; i++)
{
if(*(ptr+i) == 'p')
{
c++;
if(c < 4)
{
switch(c){
case 1:
cout << c << "st prime is: " << i << endl;
break;
case 2:
cout << c << "nd prime is: " << i << endl;
break;
case 3:
cout << c << "rd prime is: " << i << endl;
break;
default:
break;
}
}
else
cout << c << "th prime is: " << i << endl;
}
}
}
int main()
{
cout<<"Enter the value of N:\n";
cin>>N;
ptr=(char*)calloc(N,sizeof(char));
int i;
for(i=0;i<N;i++)
{
*(ptr+i)='0';
}
gen_sieve_primes();
print_all_primes();
free(ptr);
return 0;
}