Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Print all prime numbers less than or equal to N in C++
In this problem, we are given a number N and we have to print all prime numbers less than or equal to N.
Let’s take an example to understand the topic better −
Input: 10 Output: 2 3 5 7
A prime number is a number that can be divided by only one and the number itself. Example: 2, 3.
A simple approach is to iterate from 2 to N and divide the number by it. If the number is not divisible, then it’s a prime number. Print the number. Do this till the number is equal to N. This approach is not that efficient.
A more effective approach will be checking for prime number by iterating from 2 to √N.
Example
#include <bits/stdc++.h>
using namespace std;
bool isPrimeNumber(int n){
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
void printPrime(int n){
for (int i = 2; i <= n; i++) {
if (isPrimeNumber(i))
cout<<i<<" ";
}
}
int main(){
int n = 41;
cout<<"Prime numbers less than or equal to "<<n<<" are \n";
printPrime(n);
}
Output
Prime numbers less than or equal to 41 are
2 3 5 7 11 13 17 19 23 29 31 37 41
Advertisements