Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

C++ Program to check Prime Number

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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: true

Input:  n = 15
Output: false

Input:  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 function
int main()
{
    isPrime(11) ? cout << " true\n" : cout << " false\n";
    isPrime(15) ? cout << " true\n" : cout << " false\n";
    return 0;
}

Output

 true
 false

Time Complexity: O(n) 
Auxiliary Space: O(1)

Naive Approach (Optimised):

We need to check factors upto √n not till n. The resaon is suppose n has 2 factors and both are bigger than √n. Then n would be bigger than  n , which is absurd! So n has at least one factor smaller than √n if it isn’t prime.

Below is the implementation of the above idea:

C++




//  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;
  //suppose n=7 that is prime and its pair are (1,7)
  //so if a no. is prime then it can be check by numbers smaller than square root
  // of the n
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0)
            return false;
    }
    return true;
}
 
// Driver Program to test above function
int main()
{
    isPrime(4191) ? cout << " true\n" : cout << " false\n";
    isPrime(15) ? cout << " true\n" : cout << " false\n";
    return 0;
}
//this code is contributed by Prateek Kumar Singh

Output

 false
 false

Time Complexity: O(sqrt(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.
   
    /*
       1. Here i is of the form 5 + 6K where K>=0
       2. i+1, i+3, i+5 are even numbers (6 + 6K). N is not an even number
       3. Because N%2 and N%3 checks are done in the before step
       4. Hence i+1, i+3, i+5 can't be N's divisors.
       5. i+4 is 9 + 6K which is a 3 multiple.
       6. N is not a 3 multiple hence i+4 can't be it's divisor
       Hence we only check if N is a divisor of i or i+2.
    */
    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 function
int main()
{
    isPrime(4191) ? cout << " true\n" : cout << " false\n";
    isPrime(15) ? cout << " true\n" : cout << " false\n";
    return 0;
}

Output

 false
 false

Time Complexity: O(sqrt(n)) 
Auxiliary Space: O(1)

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’ if 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 factorial
long long fact(const int& p)
{
    if (p <= 1)
        return 1;
    return p * fact(p - 1);
}
 
// Function to check if the
// number is prime or not
bool 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 code
int 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

Output

True
false

Time Complexity : O(n) 
Auxiliary Space :  O(n)

Please refer complete article on Implementation of Wilson Primality test for more details.

Using Lucas Primality Test:

Given a number N, the task is to check if it is prime or not using Lucas Primality Test.

Lucas’ Test: 
A positive number n is prime if there exists an integer a (1 < a < n) such that :
a^{{n-1}}\ \equiv \ 1{\pmod n}  
And for every prime factor q of (n-1),

Example :

Input :  n = 7
Output : 7 is Prime
Explanation : let's take a = 3, 
then 3^6 % 7 = 729 % 7 = 1 (1st 
condition satisfied). Prime factors 
of 6 are 2 and 3,
3^(6/2) % 7 = 3^3 % 7 = 27 % 7 = 6
3^(6/3) % 7 = 3^2 % 7 = 9 % 7 = 2
Hence, 7 is Prime 

C++




// C++ implementation to check if a number is
// prime or not using Lucas Primality Test
#include <bits/stdc++.h>
using namespace std;
 
// function to generate prime factors of n
void primeFactors(int n, vector<int>& factors)
{
    // if 2 is a factor
    if (n % 2 == 0)
        factors.push_back(2);
    while (n % 2 == 0)
        n = n / 2;
 
    // if prime > 2 is factor
    for (int i = 3; i <= sqrt(n); i += 2) {
        if (n % i == 0)
            factors.push_back(i);
        while (n % i == 0)
            n = n / i;
    }
    if (n > 2)
        factors.push_back(n);
}
 
// this function produces power modulo
// some number. It can be optimized to
// using
int power(int n, int r, int q)
{
    int total = n;
    for (int i = 1; i < r; i++)
        total = (total * n) % q;
    return total;
}
 
bool isPrime(int n)
{
    // Base cases
    if (n <= 1 || n % 2 == 0)
        return false;
    if (n == 2)
        return true;
 
    // Generating and storing factors
    // of n-1
    vector<int> factors;
    primeFactors(n - 1, factors);
 
    // Array for random generator. This array
    // is to ensure one number is generated
    // only once
    int random[n - 3];
    for (int i = 0; i < n - 2; i++)
        random[i] = i + 2;
 
    // shuffle random array to produce randomness
    shuffle(random, random + n - 3,
            default_random_engine(time(0)));
 
    // Now one by one perform Lucas Primality
    // Test on random numbers generated.
    for (int i = 0; i < n - 2; i++) {
        int a = random[i];
        if (power(a, n - 1, n) != 1)
            return false;
 
        // this is to check if every factor
        // of n-1 satisfy the condition
        bool flag = true;
        for (int k = 0; k < factors.size(); k++) {
            // if a^((n-1)/q) equal 1
            if (power(a, (n - 1) / factors[k], n) == 1) {
                flag = false;
                break;
            }
        }
 
        // if all condition satisfy
        if (flag)
            return true;
    }
    return false;
}
 
// Driver code
int main()
{
    isPrime(11) ? cout << " true\n" : cout << " false\n";
    isPrime(15) ? cout << " true\n" : cout << " false\n";
    isPrime(1) ? cout << " true\n" : cout << " false\n";
    return 0;
}
 
// This code is contributed by Susobhan Akhuli

Output

 true
 false
 false

Time Complexity: O(n*logn)
Auxiliary Space: O(n)


My Personal Notes arrow_drop_up
Last Updated : 27 Mar, 2023
Like Article
Save Article
Similar Reads