Table of Contents
In this post, we will implement isPrime method. isPrime method will take an integer as input and determine whether the number is prime or number.
A prime number is a number which has only two divisors 1 and itself. To check if the number is prime or not, we need to see if it has any other factors other than 1 or itself. If it has, then number is not prime else number is prime.
Read also: Nth prime number in java
How do we determine a range upto which we need to check if number is factor or not?
Since a number can’t be divisible by number greater than itself. We can put upper limit as n but can we do better?
Yes, we can. A number can’t have factor greater than sqrt(n), so we can decide upper limit as sqrt(n).
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public static boolean isPrime(int num) { if (num <= 1) { return false; } for (int i = 2; i <= Math.sqrt(num); i++) { if (num % i == 0) { return false; } } return true; } |
We have used Math.sqrt method to find sqaure root of a number.
Java isPrime method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package org.arpit.java2blog; public class isPrimeMain { public static void main(String[] args) { System.out.println("is 17 Prime: "+isPrime(17)); System.out.println("is 27 Prime: "+isPrime(27)); System.out.println("is 79 Prime: "+isPrime(79)); } public static boolean isPrime(int num) { if (num <= 1) { return false; } for (int i = 2; i <= Math.sqrt(num); i++) { if (num % i == 0) { return false; } } return true; } } |
When you run above program, you will below output
is 27 Prime: false
is 79 Prime: true
That’s all about Java isPrime method.