Check if a number is sandwiched between primes in C++


Here we will see whether a number is sandwiched between primes or not. A number is said to be sandwiched between primes when the number just after it, and just below it is prime numbers. To solve this, check whether n-1 and n+1 are prime or not.

Example

 Live Demo

#include <iostream>
#include <set>
#define N 100005
using namespace std;
bool isPrime(int n) {
   if (n == 0 || n == 1)
      return false;
   for (int i=2;i<=n/2;i++)
      if (n%i == 0)
         return false;
   return true;
}
bool isSanwichedPrime(int n){
   if(isPrime(n - 1) && isPrime(n + 1))
      return true;
   return false;
}
int main() {
   int n = 642;
   if(isSanwichedPrime(n)){
      cout << n << " is Sandwiched between primes: " << n-1 <<" and " << n+1;
   } else {
      cout << n << " is not Sandwiched between primes";
   }
}

Output

642 is Sandwiched between primes: 641 and 643

Updated on: 21-Oct-2019

63 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements