
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Which is the fastest algorithm to find prime numbers using C++?
The Sieve of Eratosthenes is one of the most efficient ways to find the prime numbers smaller than n when n is smaller than around 10 million.
A program that demonstrates the Sieve of Eratosthenes is given as follows.
Example
#include <bits/stdc++.h> using namespace std; void SieveOfEratosthenes(int num) { bool pno[num+1]; memset(pno, true, sizeof(pno)); for (int i = 2; i*i< = num; i++) { if (pno[i] == true) { for (int j = i*2; j< = num; j + = i) pno[j] = false; } } for (int i = 2; i< = num; i++) if (pno[i]) cout << i << " "; } int main() { int num = 15; cout << "The prime numbers smaller or equal to "<< num <<" are: "; SieveOfEratosthenes(num); return 0; }
Output
The output of the above program is as follows.
The prime numbers smaller or equal to 15 are: 2 3 5 7 11 13
Now, let us understand the above program.
The function SieveOfEratosthenes() finds all the prime numbers that occur before num that is provided as argument. The code snippet for this is given as follows.
void SieveOfEratosthenes(int num) { bool pno[num+1]; memset(pno, true, sizeof(pno)); for (int i = 2; i*i< = num; i++) { if (pno[i] == true) { for (int j = i*2; j< = num; j + = i) pno[j] = false; } } for (int i = 2; i< = num; i++) if (pno[i]) cout << i << " "; }
The function main() sets the value of num and then prints all the prime numbers that are smaller or equal to num. This is done by calling the function SieveOfEratosthenes(). The code snippet for this is given as follows.
int main() { int num = 15; cout << "The prime numbers smaller or equal to "<< num <<" are: "; SieveOfEratosthenes(num); return 0; }
- Related Questions & Answers
- Which is the fastest implementation of Python
- Which one is the fastest between children() and find() in jQuery?
- Java Program to get prime numbers using the Sieve of Eratosthenes algorithm
- Different Methods to find Prime Numbers in C#
- Which are the fastest trains in India?
- C++ Program to Find GCD of Two Numbers Using Recursive Euclid Algorithm
- Fastest Way to multiply two Numbers
- Find the Product of first N Prime Numbers in C++
- Find First element in AP which is multiple of given Prime in C++
- Program to find Prime Numbers Between given Interval in C++
- Which is the fastest method to get the total row count for a MySQL Query?
- How to generate prime numbers using Python?
- Find HCF of two numbers without using recursion or Euclidean algorithm in C++
- Find product of prime numbers between 1 to n in C++
- Find Largest Special Prime which is less than or equal to a given number in C++
Advertisements