- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
Advertisements