Judge prime numbers

A program that determines whether a number entered in Java is a prime number. If the number is not a prime number, the maximum prime number below the input value is displayed.

Main.java


import java.util.Scanner;
public class Main{
	//Prime numbers displayed
	static int primeNum = 0;
	//Flag that determines whether the input value is primed
	static boolean isPrime = true;
	
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		int num;
		//Redo when entering numbers less than 2 or non-integers
		do {
			try {
				num = Integer.parseInt(sc.next());
				if(num < 2) {
					System.out.println("Please enter an integer greater than or equal to 2.");
				}
			}catch(NumberFormatException e) {
				System.out.println("Please enter in half-width integer.");
				num = 0;
			}
		}while(num < 2);
		//Find a prime number
		searchPrime(num);
		//Message to display
		String msg = String.format("%d is a prime number.", num);
		if(!isPrime) {//Change message if input value is not prime
			msg = String.format("%d was not a prime number. Close prime numbers%It is d."
				,num,primeNum);
		}
		System.out.println(msg);//display
		sc.close();
	}

	public static void searchPrime(int num){
		if(checkPrime(num)){//If it is a prime number, assign the argument to primeNum
			primeNum = num;
			return ;
		}//If it was not a prime number, look up one smaller number & a flag that was not a prime number
		isPrime = false;
		searchPrime(num - 1);
	}

	public static boolean checkPrime(int num){
		if(num < 2){//If it is 2 or less, it is not a prime number
			return false;
		}
		if(num == 2){//If it is 2, it is a prime number
			return true;
		}
		if(num % 2 == 0){//If it is an even number, it is not a prime number
			return false;
		}
		//Find out if it is divisible by a number greater than or equal to 3 and less than or equal to the square root of num
		for(int i = 3; i <= Math.sqrt(num); i ++){
			if(num % i == 0){//If it is divisible, it is not a prime number
				return false;
			}
		}
		//Prime number if not divisible
		return true;
	}
}

Recommended Posts

Judge prime numbers
Calculate prime numbers in Java
How to find Java prime numbers
[Ruby] A program that determines prime numbers
Try to display prime numbers using boolean type
[Java] Find prime numbers with an Eratosthenes sieve