- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- Print all prime numbers less than or equal to N in C++
- Euler’s Totient function for all numbers smaller than or equal to n in java
- Print all Semi-Prime Numbers less than or equal to N in C++
- An Interesting Method to Generate Binary Numbers from 1 to n?
- Count of Binary Digit numbers smaller than N in C++
- Count all the numbers less than 10^6 whose minimum prime factor is N C++
- Swift Program to Display All Prime Numbers from 1 to N
- Java Program to Display All Prime Numbers from 1 to N
- Kotlin Program to Display All Prime Numbers from 1 to N
- Haskell program to display all prime numbers from 1 to n
- How to Display all Prime Numbers from 1 to N in Golang?
- Count numbers (smaller than or equal to N) with given digit sum in C++
- Print all Jumping Numbers smaller than or equal to a given value in C++
- Python program to print all Prime numbers in an Interval
- Minimum numbers which is smaller than or equal to N and with sum S in C++

Advertisements