-1


Problem-To generate prime numbers.
Approach used-Sieve of erathones without using optimisation .
Problem-Code is generating only 2 and 3.

#include<stdio.h>

int main()
{
    int i,j;
    int primes[100];
    for(i=0;i<=20;i++)
    {
        primes[i]=1;
    }

    primes[0]=0;primes[1]=1;
    for(i=2;i<=20;i++)
    {
        if(primes[i]==1)
        {
            for(j=2;i*j<=20;j++){
                primes[i*j]=0;
            }
        }
    }

    for(i=2;primes[i]!=0&&i<=20;i++)
    {
        printf("%d\n",i);
    }

    return 0;
}
WhozCraig
  • 65,258
  • 11
  • 75
  • 141
Beginner
  • 721
  • 11
  • 27
  • 2
    and the question is... – bolov Jan 23 '15 at 18:50
  • Why the code not giving the desired output.It is giving only 2 and 3. – Beginner Jan 23 '15 at 18:51
  • Aside from the problem you know about, there is a potential buffer overflow in your nested loops `for(i=2;i<=20;i++)` and `for(j=2;j<=20;j++)`. When the outer loop sets `i` to 19, for example, the inner loop will iterate over `j` up to 20, and as a result it will set `primes[19*20]=0`. But 19*20=380, and `primes` was allocated with only 100 elements. – David K Jan 23 '15 at 20:37

1 Answers1

1
for(i=2;primes[i]!=0&&i<=20;i++){
  printf("%d\n",i);
}

Your primes[i]!=0 condition will cause the loop to terminate once it encounters a non-prime number, namely "4". Try separating it into its own conditional.

for(i=2;i<=20;i++){
  if (primes[i] != 0){
    printf("%d\n",i);
  }
}
Kevin
  • 74,910
  • 12
  • 133
  • 166