Friday, October 30, 2009

Chap8[D]d Sieve of Eratosthenes

Implement the following procedure to generate prime numbers from 1 to 100 into a program. This procedure is called sieve of Eratosthenes.
step 1 Fill an array num[100] with numbers from 1 to 100
step 2 Starting with the second entry in the array, set all its multiples to zero.

step 3 Proceed to the next non-zero element and set all its multiples to zero.
step 4
Repeat step 3 till you have set up the multiples of all the non-zero elements to zero
step 5 At the conclusion of step 4, all the non-zero entries left in the array would be prime numbers, so print out these numbers.


5 comments:

  1. y is a[o]=0 set to zero? how does it make diference?

    ReplyDelete
  2. Looking back, i think the code i wrote is not the Sieve of Eratosthenes. What the question asks is that for i = 2, we have to set all multiples of it (i.e 4,6,8,10....100) to 0. That is arr[4],arr[6],arr[8]...arr[100] has value 0. Then for i = 3, arr[9],arr[12]...arr[99] = 0. Then within the loop, there will be an if statement to test if the arr[i] is 0. THus if it is already 0, we can skip it and at the end the procedure, any arr[i] = 0 will not be a prime number.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. easy working

    void main()
    {clrscr();
    int arr[100],i,j,k;
    for(i=0;i<100;i++)
    arr[i]=i+1;

    for(i=1;i<100;i++)
    { if(arr[i]!=0)
    for(j=2;j*arr[i]<=100;j++)
    { k=((j*arr[i])-1);
    arr[k]=0;
    }
    }

    for(i=0;i<100;i++)
    {if(arr[i]!=0)
    printf("\n%d",arr[i]);}
    getch();
    }

    ReplyDelete
  5. can i get a dry run of this program?very difficult to understand

    ReplyDelete