C++ Program to Implement Sieve of eratosthenes to Generate Prime Numbers Between Given Range

C++Server Side ProgrammingProgramming

This is C++ program to implement Sieve of Eratosthenes to Generate Prime Numbers Between Given Range. In this method, an integer array with all elements initializes to zero.

It follows where each non-prime element’s index is marked as 1 inside the nested loops. The prime numbers are those whose index is marked as 0.

Algorithm

Begin
   Declare an array of size n and initialize it to zero
   Declare length, i, j
   Read length
   For i = 2 to n-1 do
      For j = i*i to n-1 do
         Arr[j-1]=1
      Done
   Done
   For i =1 to n do
      If(arr[i-1]==0)
         Print i
   Done
End

Example Code

#include <iostream>
const int len = 30;
int main() {
   int arr[30] = {0};
   for (int i = 2; i < 30; i++) {
      for (int j = i * i; j < 30; j+=i) {
         arr[j - 1] = 1;
      }
   }
   for (int i = 1; i < 30; i++) {
      if (arr[i - 1] == 0)
         std::cout << i << "\t";
   }
}

Output

1 2 3 5 7 11 13 17 19 23 29
raja
Published on 15-Mar-2019 06:55:58
Advertisements