1

I read about Sieve of Eratosthenes algorithm and tried to implement it, the code is getting compiled without any errors but I am getting blank output. Here is the code:-

#include <stdio.h>
#include <stdlib.h>
#define limit 100000
int main()
{
int prime[limit];
int i,j,t;
int n,m;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&m,&n);
for(i=0;i<=n;i++)
{
    prime[i]=1;
}
prime[0]=0;
prime[1]=0;
for(i=2;i<=n;i++)
{
    if(prime[i]==1)
    {    for(j=2;i*j<=n;j++)
              prime[i*j]=0;
    }
}
for(i=m;i<=n;i++)
{
    if(prime[i]!=0)
        printf("%d\n",i);
}
}


return 0;
}

2 Answers2

1

The problem is the size of your sieve array: it has to be large enough to stretch to the highest number that you wish to process, not for the number of items that you wish to find.

Your implementation is suitable for finding prime numbers up to 100, not for the first 100 primes. Since prime number 100 is 541, you need to change the size to 542:

int prime[542];

You also need to make the distinction between n-the-number-of-primes and n-the-highest-prime in your code. I would recommend keeping n for the count of primes that you wish to find, and use #define SIZE 542 for the size of the array. Make sure to use < SIZE instead of <= SIZE when accessing array elements.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

One important thing: you do not have to print prime[i] (which is 1) but i. This way you get a much more interesting output...

marom
  • 5,064
  • 10
  • 14