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

C++Server Side ProgrammingProgramming

Wheel Sieve method is used to find prime number between a given range. Wheel factorization is a graphical method for manually performing a preliminary to the Sieve of Eratosthenes that separates prime numbers from composites.

In this method, Prime numbers in the innermost circle have their Multiples in similar positions as themselves in the other circles, forming spokes of primes and their multiples. Multiple of these prime numbers in the innermost circle form spokes of composite numbers in the outer circles.

Algorithm

Begin
   Define max number
   gen_sieve_primes()
   Declare c
   Assign c = 2
   For p = 2 to max number
      If prime[p]==0
         prime[p]=1
         Mul = p multiply c
      For Mul less than max number
         prime[Mul] = -1
         Increment c
         Mul = p multiply c
      Done
   Done
   Print_all_prime()
   Assign c=0
   For i = 0 to max number
      if (prime[i] == 1)
         Increment c
   If c less than 4
      Switch(c)
         Case 1
            Print 1st prime number
         Case 2
            Print 2nd prime number
         Case 3
            Print 3rd prime number
   Else
      Print nth prime number
End

Example Code

#include <iostream>
using namespace std;
#define MAX_NUMBER 40
int prime[MAX_NUMBER];
void gen_sieve_prime(void) {
   for (int p = 2; p < MAX_NUMBER; p++) {
      if (prime[p] == 0)
         prime[p] = 1;
         int c = 2;
         int mul = p * c;
      for (; mul < MAX_NUMBER;) {
         prime[mul] = -1;
         c++;
         mul = p * c;
      }
   }
}
void print_all_prime() {
   int c = 0;
   for (int i = 0; i < MAX_NUMBER; i++) {
      if (prime[i] == 1) {
         c++;
         if (c < 4) {
            switch (c) {
               case 1:
                  cout << c << "st prime is: " << i << endl;
                  break;
               case 2:
                  cout << c << "nd prime is: " << i << endl;
                  break;
               case 3:
                  cout << c << "rd prime is: " << i << endl;
                  break;
              default:
              break;
           }
        }else
         cout << c << "th prime is: " << i << endl;
      }
   }
}
int main() {
   gen_sieve_prime();
   print_all_prime();
   return 0;
}

Output

1st prime is: 2
2nd prime is: 3
3rd prime is: 5
4th prime is: 7
5th prime is: 11
6th prime is: 13
7th prime is: 17
8th prime is: 19
9th prime is: 23
10th prime is: 29
11th prime is: 31
12th prime is: 37
raja
Published on 15-Mar-2019 06:47:04
Advertisements