Nearest prime less than given number n C++

C++Server Side ProgrammingProgramming

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
raja
Published on 29-Jun-2021 10:11:03
Advertisements