The concept of prime numbers
Prime numbers are also called prime numbers. A natural number greater than 1, except 1 and itself, is not divisible by other natural numbers called a prime number; otherwise it is called a composite number (it is stipulated that 1 is neither a prime number nor a composite number).
How to judge whether the input number is a prime number in the program?
As follows:
public static void main(String[] args) {
// TODO Auto-generated method stub
isPrime();
isPrime();
}
/**
* 判断是否为素数
*/
public static void isPrime() {
System.out.println("请输入一个自然数:");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
boolean isPrime = true;
for (int i = 2; i < num; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(num + "是素数");
} else {
System.out.println(num + "不是素数");
}
}
The console prints the result: