Monday, 6 June 2016

Checking number prime or not - Java program

As we know that a number is a prime number if it is a natural number greater than 1 and it can be divided either by 1 or by the number itself. As example - 2, 3, 5, 7, 11, 13, 17 ….

First thing that may come to mind is to have a loop that starts from 2 (as 1 will always divide it) and increment it until it reaches the number passed and divide that from the number itself if remainder is zero at any time then it is not a prime number.

That loop would look something like this -

for(int i = 2; i < num; i++){
    if(num % i == 0){
        flag = false;

But that logic can be made more efficient. If you take any number and check if it has any divisor you will find that by going that number/2 digits starting from 2 it will have a divisor, if one exists.

As example if number is 8 then you just need to check till 4 to see if it divides by any number or take 15 you just need to check till 7 to see if it divides completely by any number. We'll use the same logic to write our program to check for prime number.

Java program

import java.util.Scanner;

public class PrimeCheck {

    public static void main(String[] args) {
        // take input from the user
        Scanner sc = new Scanner(;
        System.out.println("Enter number - ");
             int num = sc.nextInt();
            boolean flag = isPrime(num);
                System.out.println(num + " is a prime number.");
                System.out.println(num + " is not a prime number.");

    private static boolean isPrime(int num){
        boolean flag = true;
        // loop from 2, increment it till number/2
        for(int i = 2; i < num/2; i++){
            // no remainder, means divides 
            if(num % i == 0){
                flag = false;
        return flag;


Enter number - 
16 is not a prime number.

Enter number - 
31 is a prime number.

Here scanner class is used to get input from the user.

That's all for this topic Checking number prime or not - Java program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

Related Topics

  1. Displaying prime numbers - Java program
  2. Count total number of times each character appears in a String
  3. Count number of words in a String
  4. How to display pyramid patterns in Java - Part1
  5. How to reverse a string in Java
  6. Armstrong number

You may also like -

>>>Go to Java Programs page

No comments:

Post a Comment