top of page
Click here to go to the home page of AskTheCode.

Java program to check Prime Number | AskTheCode

Team ATC

Updated: Mar 9, 2021

Java program to check whether a number is Prime or not | Java programming | AskTheCode

 

Problem:

Write a Java program that finds the prime numbers between 2 and 500. Your program should stop if we entered a number less than 2.

Input:

A line that contains a number N.


Output:

Line containing whether the number is Prime Number or not.


Example:

Enter the number to check whether it's prime or not: 55

55 is not a Prime Number.

Enter the number to check whether its prime or not: 5

5 is a Prime Number.

Enter the number to check whether its prime or not: 1

 

Code:

import java.util.Scanner;
public class PrimeNumber{

	public static boolean checkPrime(int n){
		boolean isPrime=true;
		for (int i = 2; i * i <= n; i++) {
			if (n % i == 0) {
				isPrime = false;
				break;
			}
		}
		if (n<2) isPrime = false;
		return isPrime;
	}
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		System.out.print("Enter the number to check whether it's prime or not: ");
		int n = sc.nextInt();
		do{
			boolean isPrime = checkPrime(n);
			if (isPrime == true)
				System.out.println(n+" is a Prime Number.");
			else
				System.out.println(n+" is not a Prime Number.");

			System.out.print("Enter the number to check whether its prime or not: ");
			n = sc.nextInt();
		}while (n >= 2);
	}
}

Recent Posts

See All

Comments


bottom of page