#include<stdio.h>
#include<limits.h>


#define num 86090000
int a[5000000]={0};
short int s[99999999];


void sieve()
{
     int i,j,p=sqrt(num);
     int k=0;

     a[k++]=2;

     for(i=3;i<=num;i=i*i)
     {             
           s[i]=1;               
     }
     s[3]=0;
     for(i=5;i<=num;i=i*i)
     {
          s[i]=1;
     }

     s[5]=0;
     for(i=7;i<=num;i=i*i)
     {
          s[i]=1;
     }
     s[7]=0;
     for(i=11;i<=num;i=i*i)
     {
          s[i]=1;
     }
     s[11]=0;
     for(i=13;i<=num;i=i*i)
     {
          s[i]=1;
     }
     s[13]=0;
     for(i=17;i<=num;i=i*i)
     {
          s[i]=1;
     }

     s[17]=0;
     for(i=19;i<=p;i+=2)
     {
             if(s[i]==0)  
             {
                      // a[k++]=i;           
              for(j=i*i;j<=num;j+=i)
              {
                   s[j]=1;

              }
             }        
     }

     for(i=3;i<=num;i+=2)
     {
            if(s[i]==0)                 
            a[k++]=i;
     }

     printf("%d",k);
     return;


}

int main()
{
    int n=0;
    int q=0;

    sieve();

    scanf("%d",&q);

    while(q--)
    {
         scanf("%d",&n);

         printf("%d\n",a[n-1]);




   }
    return 0;
}

very awkward.. But it is giving segmentaion fault. in the all loops of the sieve() function. can you find how ?

probably because the loop on lines 17 and 43 either 1) overflows the size of the arrays or 2) overflows the largest value that can be stored in an int, or 3) or both 1 and 2. Do the math manually with pencil & paper and you will see what is happening.

A segmentation fault indicates that you've accessed memory you shouldn't have. You should check variables that are being used as array indexes for these sorts of problems. This is one of those cases where you should debug with printf() to find out where your problem is. Track the value of i to see what's happening to it as you go through the loop. If you do, I guarantee you will find some very revealing information!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.