Java program to check if a number is prime or not

18 Oct, 2018
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

School MethodA 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.
// A school method based JAVA program// to check if a number is primeclass 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");    }}
true
 false

Time complexity of this solution is O(n)
Optimized School MethodWe can do following optimizations:
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
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.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)// A optimized school method based Java// program to check if a number is primeimport java.io.*;  class GFG {      static boolean 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    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");    }}Output:true
 false
Time complexity of this solution is O(√n)Primality Test (Introduction and School Method) | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPrimality Test (Introduction and School Method) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:44•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=AaNUzEHiDpI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Main Article : Primality Test | Set 1 (Introduction and School Method)References:https://en.wikipedia.org/wiki/Prime_numberhttp://www.cse.iitk.ac.in/users/manindra/presentations/FLTBasedTests.pdfhttps://en.wikipedia.org/wiki/Primality_testThis article is contributed by Ajay. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed aboveMy Personal Notes
arrow_drop_upSave
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.
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)
// A optimized school method based Java// program to check if a number is primeimport java.io.*;  class GFG {      static boolean 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    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");    }}
true
 false

Time complexity of this solution is O(√n)
Main Article : Primality Test | Set 1 (Introduction and School Method)
References:https://en.wikipedia.org/wiki/Prime_numberhttp://www.cse.iitk.ac.in/users/manindra/presentations/FLTBasedTests.pdfhttps://en.wikipedia.org/wiki/Primality_test
This article is contributed by Ajay. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
Iterate through List in Java
Java program to count the occurrence of each character in a string using Hashmap
How to Iterate HashMap in Java?
Remove first and last character of a string in Java
Program to print ASCII Value of a character
Iterate Over the Characters of a String in Java
How to Convert Char to String in Java?
How to Get Elements By Index from HashSet in Java?