Implement isPrime method in java

Previous
Next

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.

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).

We have used Math.sqrt method to find sqaure root of a number.

Java isPrime method

When you run above program, you will below output

is 17 Prime: true
is 27 Prime: false
is 79 Prime: true

That’s all about Java isPrime method.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog