题目描述
令Pi表示第i个素数。现任给两个正整数M <= N <= 10000,请输出PM到PN的所有素数。
输入描述:
输入在一行中给出M和N,其间以空格分隔。
输出描述:
输出从PM到PN的所有素数,每10个数字占1行,其间以空格分隔,但行末不得有多余空格。
输入例子:
5 27
输出例子:
11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89
97 101 103
题目摘自牛客网点击打开链接
下面是我写的代码,并测试通过。
import java.util.Scanner;
public class T5 {
public static void main(String[] args) {
int begin;
int end;
Scanner sc = new Scanner(System.in);
begin = sc.nextInt();
end = sc.nextInt();
int counterPrime=0;
int counterN=0;
int n=2;//从2开始的数字
StringBuffer sb = new StringBuffer();
while(true){
if(isPrime(n)){
counterPrime++;
if(counterPrime>=begin&&counterPrime<=end){
counterN++;
//sb.append(n+" ");
if(counterN%10==0){
sb.append(n+"\n");
}else if(counterPrime==end){
sb.append(n);
break;
}else{
sb.append(n+" ");
}
}
}
n++;
if(counterPrime==10000){
break;
}
}
System.out.println(sb.toString());
}
static boolean isPrime(int d){
if(d==1)
return false;
double result =Math.sqrt(d);
int j= (int)result;
for(int i=2;i<=j;i++)
if(d%i==0){
return false;
}
return true;
}
}
结果如图:
这道题的核心就是怎么判断素数,代码中isPrime方法为判断素数的方法,然后再注意题目的格式要求基本就能做出来,总体来说难度不大。