Related Articles

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

• Difficulty Level : Easy
• Last Updated : 07 Apr, 2021

This approach is based on Wilson’s theorem and using the fact that factorial computation can be done easily using DP
Wilson theorem says if a number k is prime then ((k-1)! + 1) % k must be 0.
Below is 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++

 `// C++ program to Prints prime numbers smaller than n``#include``using` `namespace` `std;``void` `primesInRange(``int` `n)``{``    ``// Compute factorials and apply Wilson's``    ``// theorem.``    ``int` `fact = 1;``    ``for``(``int` `k=2;k

## Java

 `// Java program prints prime numbers smaller than n``class` `GFG{``static` `void` `primesInRange(``int` `n)``{``    ``// Compute factorials and apply Wilson's``    ``// theorem.``    ``int` `fact = ``1``;``    ``for``(``int` `k=``2``;k

## Python3

 `# Python3 program to prints prime numbers smaller than n``def` `primesInRange(n) :` `    ``# Compute factorials and apply Wilson's``    ``# theorem.``    ``fact ``=` `1``    ``for` `k ``in` `range``(``2``, n):``        ``fact ``=` `fact ``*` `(k ``-` `1``)``        ``if` `((fact ``+` `1``) ``%` `k ``=``=` `0``):``            ``print` `k` `# Driver code``n ``=` `15``primesInRange(n)`

## C#

 `// C# program prints prime numbers smaller than n``class` `GFG{``static` `void` `primesInRange(``int` `n)``{``    ``// Compute factorials and apply Wilson's``    ``// theorem.``    ``int` `fact = 1;``    ``for``(``int` `k=2;k

## PHP

 ``

## Javascript

 ``

Output :

```2
3
5
7
11
13```

This article is contributed by Parikshit Mukherjee. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up