Monday, August 20, 2018

SIEVE OF ERATOSTHENES

  • Problem Description

    C Program to Read & Print Prime Numbers in a Range using Sieve of Eratosthenes.

    To find all the prime numbers less than or equal to a given integer n by Eratosthenes' method:

    Create a list of consecutive integers from 2 through n: (2, 3, 4, ..., n).

    Initially, let p equal 2, the smallest prime number.

    Enumerate the multiples of p by counting to n from 2p in increments of p, and mark them in the list (these will be 2p, 3p, 4p, ...; the p itself should not be marked).

    Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now equal this new number (which is the next prime), and repeat from step 3.

    When the algorithm terminates, the numbers remaining not marked in the list are all the primes below n.
  • CODING ARENA
  • #include <stdio.h>
    int main()
    {
        int low=2+1, high, i, flag;
        scanf("%d", &high);

        while (low < high)
        {
            flag = 0;

            for(i = 2; i <= low/2; ++i)
            {
                if(low % i == 0)
                {
                    flag = 1;
                    break;
                }
            }

            if (flag == 0)
                printf("%d\n", low);

            ++low;
        }

        return 0;
    }
  • Test Case 1

    Input (stdin)
    10
    
    
    Expected Output
    3
    
    5
    
    7
  • Test Case 2

    Input (stdin)
    20
    
    
    Expected Output
    3
    
    5
    
    7
    
    11
    
    13
    
    17
    
    19

No comments:

Post a Comment