Prime Number Program | Code to Check whether a number is Prime or not
Last Updated :
19 Jul, 2024
Given a positive integer n, write a code to check whether the number is prime.
What is Prime Number?
A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Examples of the first few prime numbers are {2, 3, 5, ...}
Examples:
Input: n = 11
Output: true
Input: n = 15
Output: false
Input: n = 1
Output: false
Standard Approaches to Check whether a number is Prime or not
School Method (Trial division method) - O(n) time & O(1) space
A simple solution is to iterate through all numbers from 2 to n-1 and check if it divides n for every number. If we find any number that divides, we return false.
Below is the implementation of this method.
C++
// 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;
}
Java
// A school method based JAVA program
// to check if a number is prime
class GFG {
static boolean 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
public static void main(String args[])
{
if (isPrime(11))
System.out.println(" true");
else
System.out.println(" false");
if (isPrime(15))
System.out.println(" true");
else
System.out.println(" false");
}
}
Python
# A school method based Python3
# program to check if a number
# is prime
def isPrime(n):
# Corner case
if n <= 1:
return False
# Check from 2 to n-1
for i in range(2, n):
if n % i == 0:
return False
return True
# Driver Program to test above function
print("true") if isPrime(11) else print("false")
print("true") if isPrime(14) else print("false")
C#
// A optimized school method based C#
// program to check if a number is prime
using System;
namespace prime {
public class GFG {
public static bool isprime(int n)
{
// Corner cases
if (n <= 1)
return false;
for (int i = 2; i < n; i++)
if (n % i == 0)
return false;
return true;
}
// Driver program
public static void Main()
{
if (isprime(11))
Console.WriteLine("true");
else
Console.WriteLine("false");
if (isprime(15))
Console.WriteLine("true");
else
Console.WriteLine("false");
}
}
}
JavaScript
// A school method based Javascript program
// to check if a number is prime
function isPrime(n)
{
// Corner case
if (n <= 1)
return false;
// Check from 2 to n-1
for (let i = 2; i < n; i++)
if (n % i == 0)
return false;
return true;
}
// Driver Program to test above function
isPrime(11) ? console.log(" true" +
"<br>")
: console.log(" false" +
"<br>");
isPrime(15) ? console.log(" true" +
"<br>")
: console.log(" false" +
"<br>");
PHP
<?php
// A school method based PHP
// program to check if a number
// is prime
function isPrime($n)
{
// Corner case
if ($n <= 1) return false;
// Check from 2 to n-1
for ($i = 2; $i < $n; $i++)
if ($n % $i == 0)
return false;
return true;
}
// Driver Code
$tet = isPrime(11) ? " true\n" :
" false\n";
echo $tet;
$tet = isPrime(15) ? " true\n" :
" false\n";
echo $tet;
?>
Time complexity: O(n)
Auxiliary Space: O(1)
Optimised School Method (Trial division method) - O(sqrt(n)) time & O(1) space
We can do the following optimizations: Instead of checking till n, we can check till √n because a larger factor of n must be a multiple of a smaller factor that has been already checked. The implementation of this method is as follows:
C++
// Optimised 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 square root of n
for (int i = 2; i <= sqrt(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;
}
// This code is contributed by Vikash Sangai
Java
// Optimised school method based JAVA program
// to check if a number is prime
class GFG {
static boolean isPrime(int n)
{
// Corner case
if (n <= 1)
return false;
// Check from 2 to square root of n
for (int i = 2; i * i <= n; i++)
if (n % i == 0)
return false;
return true;
}
// Driver Program
public static void main(String args[])
{
if (isPrime(11))
System.out.println(" true");
else
System.out.println(" false");
if (isPrime(15))
System.out.println(" true");
else
System.out.println(" false");
}
}
// This code is contributed by Vikash Sangai
Python
# Optimised school method based PYTHON program
# to check if a number is prime
# import the math module
import math
# function to check whether the number is prime or not
def isPrime(n):
# Corner case
if (n <= 1):
return False
# Check from 2 to square root of n
for i in range(2, int(math.sqrt(n)) + 1):
if (n % i == 0):
return False
return True
# Driver Program to test above function
print("true") if isPrime(11) else print("false")
print("true") if isPrime(15) else print("false")
# This code is contributed by bhoomikavemula
C#
// Optimised school method based C#
// program to check if a number is prime
using System;
namespace prime {
public class GFG {
public static bool isprime(int n)
{
// Corner cases
if (n <= 1)
return false;
for (int i = 2; i * i <= n; i++)
if (n % i == 0)
return false;
return true;
}
// Driver program
public static void Main()
{
if (isprime(11))
Console.WriteLine("true");
else
Console.WriteLine("false");
if (isprime(15))
Console.WriteLine("true");
else
Console.WriteLine("false");
}
}
}
// This code is contributed by Vikash Sangai
JavaScript
<script>
// JavaScript code for the above approach
function isPrime(n)
{
// Corner case
if (n <= 1) return false;
// Check from 2 to square root of n
for (let i = 2; i*i <= n; i++)
if (n % i == 0)
return false;
return true;
}
// Driver Code
if(isPrime(11))
document.write(" true" + "<br/>");
else
document.write(" false" + "<br/>");
if(isPrime(15))
document.write(" true" + "<br/>");
else
document.write(" false" + "<br/>");
// This code is contributed by sanjoy_62.
</script>
Time Complexity: O(√n)
Auxiliary Space: O(1)
Other Approaches to Check whether a number is Prime or not
Mathematics based approach - (Not valid for all test cases)
This approach is based on the fact that all primes greater than 3 can be represented in the form of 6k ± 1, where k is any integer greater than 0.
How to check this?
- We know that every integer can be represented in the form of (pk + q), where q lies in the range of [0, p).
- Now let us consider that p = 6, then any integer (greater than 3) can be expressed as (6k + i), where i = 0, 1, 2, 3, 4, or 5.
- So for any integer can be of the form (6k + 0), (6k + 1), (6k + 2), (6k + 3), (6k + 4), or (6k + 5).
- Now among these,
- 2 divides (6k + 0), (6k + 2), and (6k + 4), and
- 3 divides (6k + 3).
- So the remaining numbers are (6k + 1), and (6k + 5). Also (6k + 5) can be represented as (6k - 1).
- So all prime numbers can be represented as 6k ± 1.
So, a more efficient method is to test whether n is divisible by 2 or 3, then to check through all numbers of the form 6k ± 1 <= √n. This is 3 times faster than testing all numbers up to √n. (Source: Wikipedia).
(Note: this approach is not valid for all testcases)
Below is the implementation of the above approach:
C++
// C++ program to check the given number
// is prime or not
#include <bits/stdc++.h>
using namespace std;
// Function to check if the given number
// is prime or not.
bool isPrime(int n)
{
if (n == 2 || n == 3)
return true;
if (n <= 1 || n % 2 == 0 || n % 3 == 0)
return false;
// To check through all numbers of the form 6k ± 1
for (int i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0)
return false;
}
return true;
}
// Driver Code
int main()
{
isPrime(11) ? cout << " true\n" : cout << " false\n";
isPrime(15) ? cout << " true\n" : cout << " false\n";
return 0;
}
Java
// JAVA program to check the given number
// is prime or not
class GFG {
static boolean isPrime(int n)
{
// since 2 and 3 are prime
if (n == 2 || n == 3)
return true;
// if n<=1 or divided by 2 or 3 then it can not be
// prime
if (n <= 1 || n % 2 == 0 || n % 3 == 0)
return false;
// To check through all numbers of the form 6k ± 1
for (int i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0)
return false;
}
return true;
}
// Driver Program
public static void main(String args[])
{
if (isPrime(11))
System.out.println(" true");
else
System.out.println(" false");
if (isPrime(15))
System.out.println(" true");
else
System.out.println(" false");
}
}
// This code is contributed by Ujjwal Kumar Bhardwaj
Python
# Python program to check the given number
# is prime or not
# Function to check if the given number
# is prime or not.
import math
def isPrime(n):
if n == 2 or n == 3:
return True
elif n <= 1 or n % 2 == 0 or n % 3 == 0:
return False
# To check through all numbers of the form 6k ± 1
# until i <= square root of n, with step value 6
for i in range(5, int(math.sqrt(n))+1, 6):
if n % i == 0 or n % (i+2) == 0:
return False
return True
# # Driver code
print(isPrime(11))
print(isPrime(20))
# # This code is contributed by Harsh Master
C#
// C# program to check the given number
// is prime or not
using System;
class GFG {
static bool isPrime(int n)
{
// since 2 and 3 are prime
if (n == 2 || n == 3)
return true;
// if n<=1 or divided by 2 or 3 then it can not be
// prime
if (n <= 1 || n % 2 == 0 || n % 3 == 0)
return false;
// To check through all numbers of the form 6k ± 1
for (int i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0)
return false;
}
return true;
}
// Driver Program
public static void Main(String[] args)
{
if (isPrime(11))
Console.WriteLine(" true");
else
Console.WriteLine(" false");
if (isPrime(15))
Console.WriteLine(" true");
else
Console.WriteLine(" false");
}
}
// This code is contributed by Aman Kumar
JavaScript
<script>
// JavaScript program to check the given number
// is prime or not
// Function to check if the given number
// is prime or not.
function isPrime(n)
{
if (n == 2 || n == 3)
return true;
if (n <= 1 || n % 2 == 0 || n % 3 == 0)
return false;
// To check through all numbers of the form 6k ± 1
for (let i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0)
return false;
}
return true;
}
// Driver Code
isPrime(11) ? document.write(" true" + "<br/>") : document.write(" false" + "<br/>");
isPrime(15) ? document.write(" true" + "<br/>") : document.write(" false" + "<br/>");
// This code is contributed by Pushpesh Raj.
</script>
Efficient solutions
Algorithms to find all prime numbers smaller than the N.
More problems related to Prime number
Recent Articles on Prime Numbers!
Similar Reads
Check whether a number is Good prime or not Given a positive integer N, the task is to check whether the given number is good prime or not. If the given number is good prime print âYESâ Otherwise Print âNOâ. Good Prime: In Mathematics, a good prime is a prime number whose square is greater than the product of any two primes at the same number
8 min read
Check whether a number is semiprime or not Given a positive integer n. Find whether a number is a semiprime or not. Print True if number is semiprime else False. A semiprime is a natural number that is a product of two prime numbers.Examples : Input: 6Output: TrueExplanation6 is a semiprime number as it is aproduct of two prime numbers 2 and
11 min read
Check whether the given number is Euclid Number or not Given a positive integer n, the task is to check if it is Euclid Number or not. Print âYESâ if the given number is Euclid Number otherwise print âNO'. Euclid number : In Mathematics, Euclid numbers are integers of the form - E_{n} = p_{n}\# + 1 where p_{n}\# is product of first n prime numbers.The f
15 min read
Check if a number is Primorial Prime or not Given a positive number N, the task is to check if N is a primorial prime number or not. Print 'YES' if N is a primorial prime number otherwise print 'NO.Primorial Prime: In Mathematics, A Primorial prime is a prime number of the form pn# + 1 or pn# - 1 , where pn# is the primorial of pn i.e the pro
10 min read
Program to check if given number N is Prime or not Given a number N, the task is to check if the number is a prime number or not. Check if given number N is Prime or not Examples: Input: N = 11Output: trueExplanation: The number is not divisible by any number, other than 1 and 11 itself. Input: N = 35Output: falseExplanation: Apart from 1 and 35, th
12 min read
Check whether the given number is Wagstaff prime or not Given a positive integer n, the task is to check if it is a Wagstaff prime or not. Print 'YES' if the given number is Wagstaff prime otherwise print 'NO'.Wagstaff prime: In mathematics, Wagstaff prime is a prime number 'n' of the form n = \frac{2^{q} + 1}{3} where 'q' is an odd prime.First, few Wags
7 min read
Check if the number is a Prime power number Given an integer N, the task is to check if the number is a Prime power number. If yes, then print the number along with its power which is equal to N. Else print -1. A prime power is a positive integer power of a single prime number. For example: 7 = 71, 9 = 32 and 32 = 25 are prime powers, while 6
8 min read
Check whether the sum of prime elements of the array is prime or not Given an array having N elements. The task is to check if the sum of prime elements of the array is prime or not. Examples: Input: arr[] = {1, 2, 3} Output: Yes As there are two primes in the array i.e. 2 and 3. So, the sum of prime is 2 + 3 = 5 and 5 is also prime. Input: arr[] = {2, 3, 2, 2} Outpu
10 min read
Check if a prime number can be expressed as sum of two Prime Numbers Given a number n, the task is to check if it is possible to express n as the sum of two prime numbers, a and b. If such pair does not exist, return [-1, -1].Note: If [a, b] is one solution with a <= b, and [c, d] is another solution with c <= d, and a < c then [a, b] is considered as our an
9 min read
Print the nearest prime number formed by adding prime numbers to N Given a number N. The task is to print the nearest prime if the number is not prime by making it prime by adding prime numbers sequentially from 2. Examples: Input: N = 8 Output: 13 8 is not prime, so add the first prime to it to get 10 10 is not prime, hence add the second prime, i.e., 3 to get 13
11 min read