1 ImportJava.util.Scanner;2 3 /**4 * @authorSchrödinger's Cat5 * Java Determines if a number is prime6 * 7 * Primes, also known as prime numbers, refers to the number of natural numbers greater than 1 that cannot be divisible by other natural numbers except 1 and itself .*/8 Public classPrimenumber {9 Public Static voidMain (string[] args) {TenScanner sc =NewScanner (system.in);//scanner, receiving console input information OneSystem.out.println ("Please enter an integer greater than 1:"); A - Try { - intnum = Sc.nextint ();//the integer that receives the console input the - if(IsPrime (num)) {//Call the IsPrime () method -SYSTEM.OUT.PRINTLN (num + "is prime");//if the IsPrime () method returns True, the output is a prime number - +}Else { - +SYSTEM.OUT.PRINTLN (num + "not prime");//if the IsPrime () method returns FALSE, the output is not a prime number A } at -}Catch(Exception e) { - -System.out.println ("Please enter an integer");//catch exception, if input illegal number, output exception - } - sc.close (); in } - to /** + * Used to determine if a number is a prime, if yes, returns TRUE, otherwise returns false - * @paramthe value of a input the * @returntrue False*/ * $ Public Static BooleanIsPrime (inta) {Panax Notoginseng BooleanFlag =true; - the if(A<2) {//prime number not less than 2 + return false; A}Else { the for(inti = 2;i<=math.sqrt (a); i++) { + if(a% i = = 0) {//if it can be divisible, it means that it is not a prime, return false -Flag =false; $ Break; $ } - } - } the returnFlag; - }Wuyi}
java-to determine if a number is prime