An interesting solution to get all prime numbers smaller than n
This approach is based on Wilson’s theorem and uses the fact that factorial computation can be done easily using DP
Wilson’s theorem says if a number k is prime then ((k-1)! + 1) % k must be 0.
Below is a Python implementation of the approach. Note that the solution works in Python because Python supports large integers by default therefore factorial of large numbers can be computed.
C++
#include <bits/stdc++.h>
using namespace std;
void primesInRange( int n)
{
int fact = 1;
for ( int k = 2; k < n; k++) {
fact = fact * (k - 1);
if ((fact + 1) % k == 0)
cout << k << endl;
}
}
int main()
{
int n = 15;
primesInRange(n);
}
|
Java
class GFG{
static void primesInRange( int n)
{
int fact = 1 ;
for ( int k= 2 ;k<n;k++){
fact = fact * (k - 1 );
if ((fact + 1 ) % k == 0 )
System.out.println(k);
}
}
public static void main(String[] args){
int n = 15 ;
primesInRange(n);
}
}
|
Python3
def primesInRange(n) :
fact = 1
for k in range ( 2 , n):
fact = fact * (k - 1 )
if ((fact + 1 ) % k = = 0 ):
print k
n = 15
primesInRange(n)
|
C#
class GFG{
static void primesInRange( int n)
{
int fact = 1;
for ( int k=2;k<n;k++){
fact = fact * (k - 1);
if ((fact + 1) % k == 0)
System.Console.WriteLine(k);
}
}
static void Main(){
int n = 15;
primesInRange(n);
}
}
|
PHP
<?php
function primesInRange( $n )
{
$fact = 1;
for ( $k =2; $k < $n ; $k ++){
$fact = $fact * ( $k - 1);
if (( $fact + 1) % $k == 0)
print ( $k . "\n" );
}
}
$n = 15;
primesInRange( $n );
?>
|
Javascript
<script>
function primesInRange(n)
{
let fact = 1;
for (let k = 2; k < n; k++){
fact = fact * (k - 1);
if ((fact + 1) % k == 0)
document.write((k + "<br>" ));
}
}
let n = 15;
primesInRange(n);
</script>
|
Output :
2
3
5
7
11
13
Time Complexity: O(n)
Auxiliary Space: O(1)
Last Updated :
18 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...