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

C++Server Side ProgrammingProgramming

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
Published on 21-Oct-2019 08:47:54