Check if a number is sandwiched between primes | CPP Program to check whether a number is sandwiched between two primes or not ; returns true if number n is prime ; 0 and 1 both are non - primes ; finding square root of n ; checking if n has any factor upto square root of n if yes its not prime ; Driver 's Code
#include <iostream> NEW_LINE #include <cmath> NEW_LINE using namespace std ; bool isPrime ( int n ) { if ( n == 0 n == 1 ) return false ; int root = sqrt ( n ) ; for ( int i = 2 ; i <= root ; i ++ ) if ( n % i == 0 ) return false ; return true ; } bool isSandwitched ( int n ) { return ( isPrime ( n - 1 ) && isPrime ( n + 1 ) ) ; } int main ( ) { int n = 642 ; cout << n << " ▁ : ▁ " ; if ( isSandwitched ( n ) ) cout << " Yes STRNEWLINE " ; else cout << " No STRNEWLINE " ; n = 9 ; cout << n << " ▁ : ▁ " ; if ( isSandwitched ( n ) ) cout << " Yes STRNEWLINE " ; else cout << " No STRNEWLINE " ; return 0 ; }