素数就是其本身除了被1和它本身之外的任何整数都不能整除
1. 遍历法:
通过遍历从1到它身的数,再用被判断的数取整除这些数,通过计数器的方式,判断是否等于2,来判断是否为素数(最容易理解的方法,时间复杂度也最高)
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int temp = scanner.nextInt();
for(int i= 0;i<temp;i++){
int num = scanner.nextInt();
int count = 0;
for(int j = 1;j<=num;j++){
if(num%j==0){
count++;
}
}
if(count == 2){
System.out.print("Yes");
}else{
System.out.print("No");
}
}
}
}
2.简化后
除了1以外,任何合数最小的因子就是2,那最大的因子就是 n/2
那我们就从2开始遍历到 n/2就足够了
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int temp = scanner.nextInt();
for(int i= 0;i<temp;i++){
int num = scanner.nextInt();
int count = 0;
for(int j = 2;j<=num/2;j++){
if(num%j==0){
System.out.println("Yes");
}else{
System.out.println("No");
}
}
}
}
}
3.再进一步
其实不需要遍历到n/2,只需要遍历到根号n,就可以进行判断(降低时间复杂度)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int temp = scanner.nextInt();
for(int i= 0;i<temp;i++){
int num = scanner.nextInt();
int count = 0;
for(int j = 1;j<=(int)(Math.sqrt(num));j++){
if(num%j==0){
System.out.println("Yes");
}else{
System.out.println("No");
}
}
}
}
}