Java program to check Prime Number | AskTheCode

Updated: Mar 9

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);
	}
}
21 views0 comments

Recent Posts

See All

Golf CodeChef Solution in Java - AskTheCode

CodeChef May Long Challenge Solution | Golf (LKDNGOLF) solution | AskTheCode Golf (LKDNGOLF) solution Problem: It's a lockdown. You’re bored in your house and are playing golf in the hallway. The hall

Solubility - CodeChef Solution in Java and C++| AskTheCode

CodeChef May Long Challenge Solution | Solubility (SOLBLTY) solution | AskTheCode Solubility (SOLBLTY) solution Problem: Suppose for a unit rise in temperature, the solubility of sugar in water increa

Valid Paths CodeChef Solution in C++ | AskTheCode

CodeChef May Long Challenge Solution | Valid Paths (VPATH) solution | AskTheCode Valid Paths (VPATH) CodeChef solution Problem: You are given a tree with N nodes numbered from 1 to N. A set S of nodes