Primality Test | Set 1 (Introduction and School Method)

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 of first few prime numbers are {2, 3, 5,

Examples:

```Input:  n = 11
Output: true

Input:  n = 15
Output: false

Input:  n = 1
Output: false
```

Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.

School Method
A simple solution is to iterate through all numbers from 2 to n-1 and for every number check if it divides n. If we find any number that divides, we return false.

Below is C++ implementation of this method.

```// 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 of this solution is O(n)

Optimized School Method
We can do following optimizations:

1. Instead of checking till n, we can check till √n because a larger factor of n must be a multiple of smaller factor that has been already checked.
2. The algorithm can be improved further by observing that all primes are of the form 6k ± 1, with the exception of 2 and 3. This is because all integers can be expressed as (6k + i) for some integer k and for i = ?1, 0, 1, 2, 3, or 4; 2 divides (6k + 0), (6k + 2), (6k + 4); and 3 divides (6k + 3). So a more efficient method is to test if n is divisible by 2 or 3, then to check through all the numbers of form 6k ± 1. (Source: wikipedia)
3. Below is C++ implementation of this solution.

```// 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;

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

Output:

```true
false
```

Time complexity of this solution is O(√n)

Primality Test | Set 2 (Fermat Method)

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.
2.4 Average Difficulty : 2.4/5.0
Based on 30 vote(s)