Primality Test | Set 1 (Introduction and School Method)
- Difficulty Level : Easy
- Last Updated : 21 Jul, 2022
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 the first few prime numbers are {2, 3, 5, …}
Examples :
Input: n = 11
Output: true![]()
Input: n = 15
Output: falseInput: n = 1
Output: false
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 the implementation of this method.
C++
// A school method based C++ program to check if a// number is prime#include <bits/stdc++.h>usingnamespacestd;boolisPrime(intn){// Corner caseif(n <= 1)returnfalse;// Check from 2 to n-1for(inti = 2; i < n; i++)if(n % i == 0)returnfalse;returntrue;}// Driver Program to test above functionintmain(){isPrime(11) ? cout <<" true\n": cout <<" false\n";isPrime(15) ? cout <<" true\n": cout <<" false\n";return0;}Java
// A school method based JAVA program// to check if a number is primeclassGFG {staticbooleanisPrime(intn){// Corner caseif(n <=1)returnfalse;// Check from 2 to n-1for(inti =2; i < n; i++)if(n % i ==0)returnfalse;returntrue;}// Driver Programpublicstaticvoidmain(String args[]){if(isPrime(11))System.out.println(" true");elseSystem.out.println(" false");if(isPrime(15))System.out.println(" true");elseSystem.out.println(" false");}}// This code is contributed// by Nikita Tiwari.Python3
# A school method based Python3# program to check if a number# is primedefisPrime(n):# Corner caseifn <=1:returnFalse# Check from 2 to n-1foriinrange(2, n):ifn%i==0:returnFalsereturnTrue# Driver Program to test above function("true")ifisPrime(11)else("false")("true")ifisPrime(14)else("false")# This code is contributed by Smitha Dinesh SemwalC#
// A optimized school method based C#// program to check if a number is primeusingSystem;namespaceprime {publicclassGFG {publicstaticboolisprime(intn){// Corner casesif(n <= 1)returnfalse;for(inti = 2; i < n; i++)if(n % i == 0)returnfalse;returntrue;}// Driver programpublicstaticvoidMain(){if(isprime(11))Console.WriteLine("true");elseConsole.WriteLine("false");if(isprime(15))Console.WriteLine("true");elseConsole.WriteLine("false");}}}// This code is contributed by Sam007PHP
<?php// A school method based PHP// program to check if a number// is primefunctionisPrime($n){// Corner caseif($n<= 1)returnfalse;// Check from 2 to n-1for($i= 2;$i<$n;$i++)if($n%$i== 0)returnfalse;returntrue;}// Driver Code$tet= isPrime(11) ?" true\n":" false\n";echo$tet;$tet= isPrime(15) ?" true\n":" false\n";echo$tet;// This code is contributed by m_kit?>Javascript
<script>// A school method based Javascript program to check if a// number is primefunctionisPrime(n){// Corner caseif(n <= 1)returnfalse;// Check from 2 to n-1for(let i = 2; i < n; i++)if(n % i == 0)returnfalse;returntrue;}// Driver Program to test above functionisPrime(11)? document.write(" true"+"<br>"): document.write(" false"+"<br>");isPrime(15)? document.write(" true"+"<br>"): document.write(" false"+"<br>");// This code is contributed by Mayank Tyagi</script>Outputtrue falseTime complexity: O(n)
Auxiliary Space: O(1)Optimized School Method: 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>usingnamespacestd;boolisPrime(intn){// Corner caseif(n <= 1)returnfalse;// Check from 2 to square root of nfor(inti = 2; i <=sqrt(n); i++)if(n % i == 0)returnfalse;returntrue;}// Driver Program to test above functionintmain(){isPrime(11) ? cout <<" true\n": cout <<" false\n";isPrime(15) ? cout <<" true\n": cout <<" false\n";return0;}// This code is contributed by Vikash SangaiJava
// Optimised school method based JAVA program// to check if a number is primeclassGFG {staticbooleanisPrime(intn){// Corner caseif(n <=1)returnfalse;// Check from 2 to square root of nfor(inti =2; i * i <= n; i++)if(n % i ==0)returnfalse;returntrue;}// Driver Programpublicstaticvoidmain(String args[]){if(isPrime(11))System.out.println(" true");elseSystem.out.println(" false");if(isPrime(15))System.out.println(" true");elseSystem.out.println(" false");}}// This code is contributed by Vikash SangaiPython3
# Optimised school method based PYTHON program# to check if a number is prime# import the math moduleimportmath# function to check weather the number is prime or notdefisPrime(n):# Corner caseif(n <=1):returnFalse# Check from 2 to square root of nforiinrange(2,int(math.sqrt(n))+1):if(n%i==0):returnFalsereturnTrue# Driver Program to test above function("true")ifisPrime(11)else("false")("true")ifisPrime(15)else("false")# This code is contributed by bhoomikavemulaC#
// Optimised school method based C#// program to check if a number is primeusingSystem;namespaceprime {publicclassGFG {publicstaticboolisprime(intn){// Corner casesif(n <= 1)returnfalse;for(inti = 2; i * i <= n; i++)if(n % i == 0)returnfalse;returntrue;}// Driver programpublicstaticvoidMain(){if(isprime(11))Console.WriteLine("true");elseConsole.WriteLine("false");if(isprime(15))Console.WriteLine("true");elseConsole.WriteLine("false");}}}// This code is contributed by Vikash SangaiJavascript
<script>// JavaScript code for the above approachfunctionisPrime(n){// Corner caseif(n <= 1)returnfalse;// Check from 2 to square root of nfor(let i = 2; i*i <= n; i++)if(n % i == 0)returnfalse;returntrue;}// Driver Codeif(isPrime(11))document.write(" true"+"<br/>");elsedocument.write(" false"+"<br/>");if(isPrime(15))document.write(" true"+"<br/>");elsedocument.write(" false"+"<br/>");// This code is contributed by sanjoy_62.</script>Outputtrue falseTime Complexity: √n
Auxiliary Space: O(1)Another approach: It is based on the fact that all primes greater than 3 are of the form 6k ± 1, where k is any integer greater than 0. This is because all integers can be expressed as (6k + i), where i = −1, 0, 1, 2, 3, or 4. And note that 2 divides (6k + 0), (6k + 2), and (6k + 4) and 3 divides (6k + 3). 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).
Below is the implementation of the above approach:
C++
// C++ program to check the given number// is prime or not#include <bits/stdc++.h>usingnamespacestd;// Function to check if the given number// is prime or not.boolisPrime(intn){if(n == 2 || n == 3)returntrue;if(n <= 1 || n % 2 == 0 || n % 3 == 0)returnfalse;// To check through all numbers of the form 6k ± 1for(inti = 5; i * i <= n; i += 6) {if(n % i == 0 || n % (i + 2) == 0)returnfalse;}returntrue;}// Driver Codeintmain(){isPrime(11) ? cout <<" true\n": cout <<" false\n";isPrime(15) ? cout <<" true\n": cout <<" false\n";return0;}Java
// JAVA program to check the given number// is prime or notclassGFG {staticbooleanisPrime(intn){// since 2 and 3 are primeif(n ==2|| n ==3)returntrue;// if n<=1 or divided by 2 or 3 then it can not be primeif(n <=1|| n %2==0|| n %3==0)returnfalse;// To check through all numbers of the form 6k ± 1for(inti =5; i * i <= n; i +=6){if(n % i ==0|| n % (i +2) ==0)returnfalse;}returntrue;}// Driver Programpublicstaticvoidmain(String args[]){if(isPrime(11))System.out.println(" true");elseSystem.out.println(" false");if(isPrime(15))System.out.println(" true");elseSystem.out.println(" false");}}// This code is contributed by Ujjwal Kumar BhardwajPython3
# Python program to check the given number# is prime or not# Function to check if the given number# is prime or not.importmathdefisPrime(n):ifn==2orn==3:returnTrueelifn <=1orn%2==0orn%3==0:returnFalse# To check through all numbers of the form 6k ± 1# until i <= square root of n, with step value 6foriinrange(5,int(math.sqrt(n))+1,6):ifn%i==0orn%(i+2)==0:returnFalsereturnTrue# # Driver code(isPrime(11))(isPrime(20))# # This code is contributed by Harsh MasterOutputtrue falseTime Complexity: √n
Auxiliary Space: O(1)My Personal Notes arrow_drop_upRecommended ArticlesPage :Article Contributed By :Improved By :Article Tags :Practice Tags :



