Hello everyone

I am trying to apply Sieve of Eratosthenes in program, but its not working.
Here is my code:--

#include<stdio.h>
long long arr[10000]={0};
int main() {
    long long i,j,num,inc=2,m=0;
    num=5000;
    for(i=0;i<num;i++)arr[i]=i;
    for(i=2;i<=num/2;i++){
       if(arr[i]>0) {
          for(j=inc*i;arr[j]<=num;j=j+i)
            arr[j]=-1;
           inc++;
      }
    }
    for(i=0;i<num;i++)printf("%lld  ",arr[i]);
    printf("\n");
    return 0;
}

This code is working for num=50 but not for num=500 or more, I don't understand why..?

Your j index is out of bounds because the inner loop test is arr[j] <= num rather than j <= num . You want to test the index, not the value stored at that index.

ohh what a mess I was doing......!
Thanks Narue..:)

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.