上海交通大学 Prime Number(java)

题目描述
Output the k-th prime number.
输入描述:
k≤10000
输出描述:
The k-th prime number.
示例1
输入
复制
3
7
输出
复制
5
17
import java.util.*;
import java.io.*;
import java.text.* ;
public class Main
{
    public static void main(String[] args) throws ParseException{
    	try {
	        BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
	        String str;
	        while((str=br.readLine()) != null) {
	        	int num = Integer.parseInt(str);
	        	int count = 0;
	        	int n = 2;
	        	while(count <= num) {
	        		if(isPrime(n)) {
	        			count++;
	        			if(count == num) break;
	        		}
	        		n++;
	        	}
	        	System.out.println(n);
	        }
 	    } catch (IOException e) {
	        e.printStackTrace();
	    }
    }
	public static boolean isPrime(int a) {
		 
		boolean flag = true;
 
		if (a < 2) {// 素数不小于2
			return false;
		} else {
 
			for (int i = 2; i <= Math.sqrt(a); i++) {
 
				if (a % i == 0) {// 若能被整除,则说明不是素数,返回false
 
					flag = false;
					break;// 跳出循环
				}
			}
		}
		return flag;
	}
}
发布了231 篇原创文章 · 获赞 22 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43306331/article/details/104187604
今日推荐