- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Nearest prime less than given number n C++
We are given a number n, we need to find the nearest prime number that is less than n. We can find the number easily if we start checking from the n - 1. Let's see some examples.
Input
10
Output
7
Algorithm
- Initialise the number n.
- Write a loop that iterates from n - 1 to 1
- Return the first prime number that you found
- Return -1 if you didn't find any prime that's less than given n
Implementation
Following is the implementation of the above algorithm in C++
#include <bits/stdc++.h> using namespace std; bool isPrime(int n) { if (n == 2) { return true; } for (int i = 2; i <= ceil(sqrt(n)); i++) { if (n % i == 0) { return false; } } return true; } int getNearestPrimeNumber(int n) { for (int i = n - 1; i > 1; i--) { if (isPrime(i)) { return i; } } return -1; } int main() { int n = 20; cout << getNearestPrimeNumber(n) << endl; return 0; }
Output
If you run the above code, then you will get the following result.
19
- Related Articles
- Java Program to display a prime number less than the given number
- Count pairs with sum as a prime number and less than n in C++
- Kth prime number greater than N in C++
- Find Largest Special Prime which is less than or equal to a given number in C++
- Print all prime numbers less than or equal to N in C++
- Print the nearest prime number formed by adding prime numbers to N
- Print all Prime Quadruplet of a number less than it in C++
- Print all Semi-Prime Numbers less than or equal to N in C++
- Count all the numbers less than 10^6 whose minimum prime factor is N C++
- Nearest Prime to a number - JavaScript
- Largest number less than N with digit sum greater than the digit sum of N in C++
- Number of elements less than or equal to a given number in a given subarray in C++
- Finding nearest prime to a specified number in JavaScript
- Count ordered pairs with product less than N in C++
- Print a number strictly less than a given number such that all its digits are distinct in C++

Advertisements