- 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++
- Print all Prime Quadruplet of a number less than it in C++
- Print triplets with sum less than or equal to k in C Program
- Print all Jumping Numbers smaller than or equal to a given value in C++
- Find Largest Special Prime which is less than or equal to a given number in C++
- An interesting solution to get all prime numbers smaller than n?
- Minimum swaps required to bring all elements less than or equal to k together in C++
- Euler’s Totient function for all numbers smaller than or equal to n in java
- C++ program to find unique pairs such that each element is less than or equal to N
- Find three integers less than or equal to N such that their LCM is maximum in C++
- How to find numbers in an array that are greater than, less than, or equal to a value in java?

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

#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); }

Prime numbers less than or equal to 41 are

2 3 5 7 11 13 17 19 23 29 31 37 41

Advertisements