检查数字是否夹在C ++中的质数之间
在这里,我们将看到数字是否夹在素数之间。当紧随其后的数字是质数时,一个数字被称为夹在质数之间。要解决此问题,请检查n-1和n+1是否为质数。
示例
#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"; } }
输出结果
642 is Sandwiched between primes: 641 and 643