java program to check prime number

This is easy question. It may not be asked you directly, but you can use this program to create many other complex program.
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.

Program logic:

If any number which is not divisible by any other number which is less than or equal to square root of that number, then it is prime number.
Lets create java program for it:

Run above program, you will get following output:

Please go through java interview programs for more such programs.

Was this post helpful?

Comments

  1. You can make this algorithm 2 times faster skipping division by even numbers:

    for (int i = 2; i <=Math.sqrt(number); i+= (i>2 ? 2 : 1)) {

    }

Leave a Reply

Your email address will not be published. Required fields are marked *