Check if the given number is prime or not in Java

In this program, we will learn two java programs using to check if a number is prime or not. This is done using a for loop and while loop in java.

How the program will work?

  • If num is divisible, flag is set “1” and we break out of loop. This is not prime.
  • If num isn’t divisible by any number, flag is “0” and number is prime number.

Let’s write this logic in a java program.

Example:

num = 106
loop till num/2
if num %2 == 0
than is prime
else
not prime

Example 1: Program to check if the given number is prime or not using for loop.

In this program, we will use for loop that is used to determine if the given number “num” is prime or not. Here, we are looping from 2 to num/2. it is because a number is not divisible by more than its half.

import java.util.Scanner;
public class Prime_number_program {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        int flag = 0;

        for (int i=2;i<=num/2;i++){
            if(num%i==0){
                flag =1;
                break;
            }
        }
        if(flag==0){
            System.out.println(num+" is a prime number");
        }
        else {
            System.out.println(num+" is not a prime number");
        }

    }
}

Output:

29
29 is  a prime number

Example 1: Program to check if the given number is prime or not using a while loop.

In this program, while loop is used instead of a for loop. The loop rune until i<=num/2. On each iteration, whether num is divisible by i is checked and the value of i is incremented by 1.

import java.util.Scanner;
public class Prime_number_program {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        int flag = 0, i=2;

        while (i<=num/2){

            if(num%2==0){
                flag =1;
                break;
            }
            i++;
        }

        if(flag==0){
            System.out.println(num+" is a prime number");
        }
        else {
            System.out.println(num+" is not a prime number");
        }

    }
}

Output:

13
13 is a prime number

Recommended:

Leave a Comment

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

x