public class Demo1 {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) { // 要习惯Scanner这种写法,牛客网上很多题都要求这样写
while (scanner.hasNextInt()) {
int num = scanner.nextInt();
if (isSushu(num)) {
System.out.println(num + "是素数");
} else {
System.out.println(num + "不是素数");
}
}
}
}
// 判断1个整数是不是素数
public static boolean isSushu(int num) {
if (num <= 1) { // 1、0、负数肯定不是素数
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) { // 根据整数的性质,这里只需要循环到Math.sqrt即平方根就可以了
if (num % i == 0) { // 除了1和它本身还有其他约数
return false;
}
}
return true;
}
}
如果大家需要视频版本讲解,欢迎大家关注我的B站: