- 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

# 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

- Related Questions & Answers
- Print all Semi-Prime Numbers less than or equal to N in C++
- Find all factorial numbers less than or equal to n in C++
- Find maximum product of digits among numbers less than or equal to N in C++
- Print all numbers less than N with at-most 2 unique digits in C++
- Count all the numbers less than 10^6 whose minimum prime factor is N C++
- Recursive program to print all numbers less than N which consist of digits 1 or 3 only in C++
- Print all Prime Quadruplet of a number less than it in C++
- Print all Jumping Numbers smaller than or equal to a given value in C++
- Print triplets with sum less than or equal to k in C Program
- Nearest prime less than given number n C++
- Find Multiples of 2 or 3 or 5 less than or equal to N in C++
- An interesting solution to get all prime numbers smaller than n?
- Find Largest Special Prime which is less than or equal to a given number in C++
- Euler’s Totient function for all numbers smaller than or equal to n in java
- Find unique pairs such that each element is less than or equal to N in C++

Advertisements