Home » Sieve of Eratosthenes

Sieve of Eratosthenes

Introduction

Sieve of Eratosthenes is an algorithm that searches for all prime numbers in the given limit. It was developed by the Greek astronomer Eratosthenes. This algorithm is very simple to compute the prime number. In the beginning, we write all the numbers between 2 and n. We mark all appropriate multiples of 2 as a composite (because 2 is the smallest prime number), and then mark all appropriate multiples of 3, and this process runs up to n.

Algorithm of Sieve of Eratosthenes

Example:

Find the all prime numbers less than the 25.

Step: 1 Write all the prime number between 2 to 25.

2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

Step: 2 According to the algorithm we mark all appropriate multiples of 2 as a composite (because 2 is the smallest prime number and the first number of the list)

2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

Step: 3 The next number of the list after 2 is 3, we mark all appropriate multiples of 3

2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

Step: 4 The next number in the list after 3 is 5 which has not yet been crossed; we mark all appropriate multiples of 5

2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

Step: 5 The next number in the list after 5 is 7 which has not yet been crossed; we mark all appropriate multiples of 7

2 34 56 78 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

Step: 6 This process will run until n.

2 3 5 7 11 13 17 19 23

Advantages of Sieve of Eratosthenes:

  1. It is a very efficient algorithm to filter out the prime numbers.
  2. Its implementation is very low.

Program

C++ language of Sieve of Eratosthenes:

Output:

Enter the number  10  Prime numbers:  2 3 5 7  

Java program

Output:

Enter the number  25  List of prime numbers upto given number are :  2   3   5   7   11   13   17   19   23  

Next TopicVigenere Cipher

You may also like