C++ Program to check Prime Number
Given a positive integer, check if the number is prime or not. A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Examples:
Input: n = 11
Output: trueInput: n = 15
Output: falseInput: n = 1
Output: false
Naive approach:
CPP
// A school method based C++ program to check if a// number is prime#include <bits/stdc++.h>using namespace std;bool isPrime(int n){ // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (int i = 2; i < n; i++) if (n % i == 0) return false; return true;}// Driver Program to test above functionint main(){ isPrime(11) ? cout << " true\n" : cout << " false\n"; isPrime(15) ? cout << " true\n" : cout << " false\n"; return 0;} |
true false
Time Complexity: O(n)
Auxiliary Space: O(1)
Optimized School Method:
CPP
// A optimized school method based C++ program to check// if a number is prime#include <bits/stdc++.h>using namespace std;bool isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; // Using concept of prime number // can be represented in form of // (6*n + 1) or(6*n - 1) hence // we have to go for every multiple of 6 and // prime number would always be 1 less or 1 more than // the multiple of 6. for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true;}// Driver Program to test above functionint main(){ isPrime(4191) ? cout << " true\n" : cout << " false\n"; isPrime(15) ? cout << " true\n" : cout << " false\n"; return 0;} |
false false
Please refer complete article on Primality Test | Set 1 (Introduction and School Method) for more details!
Using Wilson’s theorem:
Given a number N, the task is to check if it is prime or not using Wilson Primality Test. Print ‘1’ isf the number is prime, else print ‘0’.
Wilson’s theorem states that a natural number p > 1 is a prime number if and only if
(p - 1) ! ≡ -1 mod p OR (p - 1) ! ≡ (p-1) mod p
Example :
Input: p = 15 Output: Yes (p-1)! = 14! = 87178291200 87178291200 % 15 = 0
C++
// C++ implementation to check if a number is// prime or not using Wilson Primality Test#include <bits/stdc++.h>using namespace std;// Function to calculate the factoriallong long fact(const int& p){ if (p <= 1) return 1; return p * fact(p - 1);}// Function to check if the// number is prime or notbool isPrime(const long long& p){ if (p == 4) return false; // (p - 1) ! ≡ (p-1) mod p long long a = fact(p - 1) % p; if (a == p - 1) return true; return false;}// Driver codeint main(){ if (isPrime(13) == true) cout << "True" << endl; else cout << "false" << endl; if (isPrime(15) == true) cout << "True" << endl; else cout << "false" << endl; return 0;}// this code is contributed by devendra solunke |
True false
Please refer complete article on Implementation of Wilson Primality test for more details!



