;

Java Program to Check Whether a Number is Prime or Not


Tutorialsrack 29/06/2021 Java

In this Java program, you’ll learn how to check whether a number is prime or not. 

What is the Prime Number?

A prime number (or a prime) is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers and dividing by 1 or itself. In other words, prime numbers can't be divided by other numbers than itself or 1.

For example, 7 is prime because the only ways of writing it as a product, 1 × 7 or 7 × 1, involve 7 itself.

Here is the code of the program to check the given number is prime or not:

Example 1: Java Program to Check Prime Number Using a For Loop

In this program, you will see how to check whether a number is prime or not using For Loop.

Example 1: Java Program to Check Prime Number Using a For Loop
//Java Program to Check Whether a Number is Prime or Not using For Loop
 
import java.util.Scanner;
 
public class JavaPrograms {
 
	public static void main(String[] args) {
		int num;
 
		Scanner sc = new Scanner(System.in);
 
		System.out.println("Enter a Number: ");
		num = sc.nextInt();
 
		boolean flag = false;
		for (int i = 2; i <= num / 2; ++i) {
			// condition for non-prime number
			if (num % i == 0) {
				flag = true;
				break;
			}
		}
 
		if (!flag)
			System.out.println(num + " is a prime number.");
		else
			System.out.println(num + " is not a prime number.");
	}
}
Output

Enter a Number: 

7

7 is a prime number.

Example 2: Java Program to Check Prime Number Using a While Loop

In this program, you will see how to check whether a number is prime or not using While Loop.

Example 2: Java Program to Check Prime Number Using a While Loop
//Java Program to Check Whether a Number is Prime or Not using While Loop

import java.util.Scanner;

public class JavaPrograms {

	public static void main(String[] args) {
		int num, i = 2;

		Scanner sc = new Scanner(System.in);

		System.out.println("Enter a Number: ");
		num = sc.nextInt();

		boolean flag = false;
		while (i <= num / 2) {
			// condition for non-prime number
			if (num % i == 0) {
				flag = true;
				break;
			}

			++i;
		}

		if (!flag)
			System.out.println(num + " is a prime number.");
		else
			System.out.println(num + " is not a prime number.");
	}
}
Output

Enter a Number: 

11

11 is a prime number.


Related Posts



Comments

Recent Posts
Tags