Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 using Wilson's theorem. According to Wilson's theorem, if a number k is prime, then ((k - 1)! + 1) mod k will be 0. This approach provides a mathematical foundation for prime detection.
Note: This method is primarily of theoretical interest because factorial calculations grow extremely large, making it impractical for larger values of n in standard programming languages.
Syntax
void genAllPrimes(int n); // Generates all prime numbers less than n using Wilson's theorem
Algorithm
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: Wilson's Theorem Implementation
The following C program demonstrates Wilson's theorem for finding primes smaller than n −
#include <stdio.h>
void genAllPrimes(int n) {
int fact = 1;
printf("Prime numbers less than %d: ", n);
for (int i = 2; i < n; i++) {
fact = fact * (i - 1);
if ((fact + 1) % i == 0) {
printf("%d ", i);
}
}
printf("<br>");
}
int main() {
int n = 10;
genAllPrimes(n);
return 0;
}
Prime numbers less than 10: 2 3 5 7
How Wilson's Theorem Works
- Wilson's Theorem: A natural number p > 1 is prime if and only if ((p-1)! + 1) ? 0 (mod p)
- For each number i from 2 to n-1, we calculate the factorial (i-1)! incrementally
- If ((i-1)! + 1) is divisible by i, then i is prime
Limitations
- Factorial Overflow: Factorials grow exponentially, causing integer overflow for small values of n
- Inefficiency: Time complexity is O(n²) compared to O(n log log n) for the Sieve of Eratosthenes
- Practical Limit: Works reliably only for very small values due to arithmetic limitations
Note: This implementation works for demonstration with small values (n ? 10) but will fail for larger inputs due to integer overflow in factorial calculation.
Conclusion
Wilson's theorem provides an elegant mathematical approach to prime detection, but its practical application is limited by factorial overflow. For efficient prime generation, algorithms like the Sieve of Eratosthenes are preferred in real-world applications.
