
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- 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++
- Recursive program to print all numbers less than N which consist of digits 1 or 3 only in C++
- Print all Jumping Numbers smaller than or equal to a given value in C++
- Print all numbers less than N with at-most 2 unique digits in C++
- Find maximum product of digits among numbers less than or equal to N in C++
- Print all Prime Quadruplet of a number less than it in C++
- Count all the numbers less than 10^6 whose minimum prime factor is N C++
- Euler’s Totient function for all numbers smaller than or equal to n in java
- Print triplets with sum less than or equal to k in C Program
- An interesting solution to get all prime numbers smaller than n?
- Find Multiples of 2 or 3 or 5 less than or equal to N in C++
- Find Largest Special Prime which is less than or equal to a given number in C++
- Nearest prime less than given number n C++
- Linear magnification produced by a concave mirror may be:(a) less than 1 or equal to 1 (b) more than 1 or equal to 1(c) less than 1, more than 1 or equal to 1 (d) less than 1 or more than 1

Advertisements