
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
Advertisements