Help in Sieve of Eratosthenes algorithm

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 :slight_smile:
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;
}

I didn’t understand where the problem is, I tried on ideone and it seems to work for N=1000

1 Like

Is the problem with my P.C. then?
I’m using an Intel celeron Win 7 32-bit PC …a little slow
But Hope to get help to make this code more optimized…
Thanks by the way.

I had written a blog on seive for primes…If u want u can check thus out!!It also has a code link…Blog

1 Like

plz sombody tells me
how this code work?
#define N 51000000
unsigned int prime[N / 64];
#define gP(n) (prime[n>>6]&(1<<((n>>1)&31)))
#define rP(n) (prime[n>>6]&=~(1<<((n>>1)&31)))
void sieve()
{
memset( prime, -1, sizeof( prime ) );

unsigned int i;
unsigned int sqrtN = ( unsigned int )sqrt( ( double )N ) + 1;
for( i = 3; i < sqrtN; i += 2 ) if( gP( i ) )
{
    unsigned int i2 = i + i;
    for( unsigned int j = i * i; j < N; j += i2 ) rP( j );
}

}