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:

package org.arpit.java2blog;

public class PrimeNumberMain {

 public static void main(String[] args) {

  System.out.println("17 is prime number?: "+isPrime(17));
  System.out.println("2 is prime number?: "+isPrime(2));
  System.out.println("91 is prime number?: "+isPrime(91));
  System.out.println("29 is prime number?: "+isPrime(29));
  System.out.println("81 is prime number?: "+isPrime(81));
 }

 public static boolean isPrime(int number)
 {
  for (int i = 2; i <=Math.sqrt(number); i++) {
   if(number%i==0)
    return false;
  }
  return true;
 }

}

Run above program, you will get following output:

17 is prime number?: true
2 is prime number?: true
91 is prime number?: false
29 is prime number?: true
81 is prime number?: false

Please go through java interview programs for more such programs.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

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 *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.