7-4 判断素数 (10分)

本题的目标很简单,就是判断一个给定的正整数是否素数。

输入格式:
输入在第一行给出一个正整数N(≤ 10),随后N行,每行给出一个小于2
​31
​​ 的需要判断的正整数。

输出格式:
对每个需要判断的正整数,如果它是素数,则在一行中输出Yes,否则输出No。

输入样例:
2
11
111

输出样例:
Yes
No

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

//** Class for buffered reading int and double values *//*
class Reader {
	static BufferedReader reader;
	static StringTokenizer tokenizer;

	// ** call this method to initialize reader for InputStream *//*
	static void init(InputStream input) {
		reader = new BufferedReader(new InputStreamReader(input));
		tokenizer = new StringTokenizer("");
	}

	// ** get next word *//*
	static String next() throws IOException {
		while (!tokenizer.hasMoreTokens()) {
			// TODO add check for eof if necessary
			tokenizer = new StringTokenizer(reader.readLine());
		}
		return tokenizer.nextToken();
	}
	static boolean hasNext()throws IOException {
		return tokenizer.hasMoreTokens();
	}
	static String nextLine() throws IOException{
		return reader.readLine();
	}
	static char nextChar() throws IOException{
		return next().charAt(0);
	}
	static int nextInt() throws IOException {
		return Integer.parseInt(next());
	}

	static float nextFloat() throws IOException {
		return Float.parseFloat(next());
	}
}
public class Main {
	public static void main(String[] args) throws IOException {
		Reader.init(System.in);
		int n = Reader.nextInt();
		for (int i = 0; i < n; i++) {
			int m = Reader.nextInt();
			if (isPrime(m)) {
				System.out.println("Yes");
			}else {
				System.out.println("No");
			}
		}
	}

	public static boolean isPrime(int num) {
		if(num==2||num==3) {
			return true;
		}
		if (num==1||num%6!=1&&num%6!=5) {
			return false;
		}
		int temp = (int) Math.sqrt(num);
		for (int i = 5; i < temp; i+=6) {
			if (num%i==0||num%(i+2)==0) {
				return false;
			}
		}
		return true;
	}
	

}



你可能感兴趣的:(pta)