![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements