算法笔记7
2024/4/18
第四讲 数学知识
1. 质数
质数: 大于1,比如:2, 3, 5, 7, 11......等只含有1和本身,这两个约数
acwing 866. 试除法判定质数 https://www.acwing.com/problem/content/868/
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
int x = sc.nextInt();
if (isPrime(x)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
sc.close();
}
public static boolean isPrime(int x) {
if (x < 2) {
return false;
}
int sqrt = (int)Math.pow(x, 0.5);
for (int i = 2; i <= sqrt; i++) {
if (x % i == 0) {
return false;
}
}
return true;
}
}