Let Us C (Chapter 8 : Arrays) : Program-4

(d) Implement the following procedure to generate prime numbers from 1 to 100 into a program. This procedure is called sieve of Eratosthenes.
Step1: Fill an array num[100] with numbers from 1 to 100
Step2: Starting with the second entry in the array, set all its multiples to zero.
Step3: Proceed to the next non-zero element and set all its multiples to zero.
Step4: Repeat step 3 till you have set up the multiples of all the non-zero elements to zero
Step5: At the conclusion of step 4, all the non-zero entries left in the array would be prime numbers, so print out these numbers. 

let us c chapter 8 arrays problem 4
// Let Us C (Chapter 8 : Arrays) : Program-1
/* Implement the following procedure to generate prime numbers from 1 to 100 into a program. 
This procedure is called sieve of Eratosthenes.
Step1: Fill an array num[100] with numbers from 1 to 100
Step2: Starting with the second entry in the array, set all its multiples to zero.
Step3: Proceed to the next non-zero element and set all its multiples to zero.
Step4: Repeat step 3 till you have set up the multiples of all the non-zero elements to zero
Step5: At the conclusion of step 4, all the non-zero entries left in the array would be prime 
numbers, so print out these numbers */
#include<stdio.h>
#define N 100
int num[N],i=0,j=1,count=0;
void main()
{
    clrscr();
    printf("Program to implement sieve of Eratosthenes to generate prime numbers\n");
    while(i<N)    // Step1 : Fill array with natural numbers
    {
        num[i++]=j++;
    }
    for(i=1;i<N;i++) // Step4
    {
        if(num[i] != 0)
        {
            printf("%2d ",num[i]); // Step5
            count++;
        }
        for(j=1;j<N;j++)
        {
            if(num[i+(num[i]*j)] > N)    // Check exceeding array
                break;
            else
                num[i+(num[i]*j)] = 0; // Step2, Step3
        }
    }
    printf("\nTotal Prime numbers upto %d = %d",N,count);
}
OUTPUT
let us c chapter 8 arrays problem 4 output

Comments

Popular posts from this blog

Chapter 5 : Functions & Pointers (Let us C)

Let Us C (Chapter 8 : Arrays) : Program-9

Chapter 3: The Loop Control Structure (Let Us C)