An interesting solution to get all prime numbers smaller than n?


Here we will see how to generate all prime numbers that are less than n in an efficient way. In this approach we will use the Wilson’s theorem. According to his theorem if a number k is prime, then ((k - 1)! + 1) mod k will be 0. Let us see the algorithm to get this idea.

This idea will not work in C or C++ like language directly, because it will not support the large integers. The factorial will generate large numbers.

Algorithm

genAllPrime(n)

Begin
   fact := 1
   for i in range 2 to n-1, do
      fact := fact * (i - 1)
      if (fact + 1) mod i is 0, then
         print i
      end if
   done
End

Example

#include <iostream>
using namespace std;
void genAllPrimes(int n){
   int fact = 1;
   for(int i=2;i<n;i++){
      fact = fact * (i - 1);
      if ((fact + 1) % i == 0){
         cout<< i << " ";
      }
   }
}
int main() {
   int n = 10;
   genAllPrimes(n);
}

Output

2 3 5 7

Updated on: 02-Jul-2020

69 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements