62,620
社区成员
发帖
与我相关
我的任务
分享import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/*1013. 数素数 (20)
时间限制
100 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
CHEN, Yue
令Pi表示第i个素数。现任给两个正整数M <= N <= 10^4,请输出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*/
/*检索素数,放到集合里
* 遍历器控制输出
* 改进:检索到第N个素数输出M到N个数
*/
public class Test1013改进 {
public static void main(String[] args) throws IOException{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
int one=0;
int hasRead = br.read();
int j = 0,M = 0, N = 0;
while (true) {
if (hasRead >= '0' && hasRead <= '9') {
one=one*10+hasRead-48;
hasRead = br.read();
} else if (hasRead == ' ') {
if (j == 0) {
M =one;
j++;
} else{
N =one;
}
hasRead = br.read();
one = 0;
} else {
if (j == 0) {
M = one;
j++;
} else{
N =one;
}
break;
}
}
br.close();
int Arr[] = new int[N + 1];
for (int i = 1, k = 0; k <= N; i++) {
// 判断是不是素数,bool一旦为false直接结束
boolean bool = true;
for (j = (int) Math.sqrt(i); bool == true && j > 1; j--) {
if (i % j == 0)
bool = false;
}
if (bool == true) {
Arr[k] = i;
k++;
}
}
j = 1;
for (int i = M; i <= N; i++, j++) {
System.out.print(Arr[i]);
if (j % 10 == 0)
System.out.println();
if (i != N && j % 10 != 0) {
System.out.print(" ");
}
}
}
}
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Primes{
public static void main(String[] args){
System.out.print("Input PM & PN:");
Scanner keyboard = new Scanner(System.in);
String content = keyboard.nextLine();
Date start = new Date();
String regex = "\\s*(\\d+)\\s+(\\d+)\\s*";
Matcher matcher = Pattern.compile(regex).matcher(content);
if(!matcher.matches()){
System.err.println("Illegal Arguments!");
System.exit(1);
}
int pm = Integer.valueOf(matcher.group(1));
int pn = Integer.valueOf(matcher.group(2));
printPrimes(pm,pn);
Date end = new Date();
long time = end.getTime() - start.getTime();
System.out.printf("\ntime:%dms\n",time);
}
private static void printPrimes(int startIndex,int endIndex){
if(startIndex > endIndex || startIndex < 1){
System.err.println("Illegal Arguments!");
return;
}
ArrayList<Long> primes = new ArrayList<>();
primes.add(2L);
primes.add(3L);
long number = 5;
long sqrt = 0L;
long prime = 0L;
int size = 0;
for(int count = 2; count < endIndex ; count ++){
sqrt = (long)(Math.sqrt(number) + 1);
size = primes.size();
for(int index = 0;index < size && primes.get(index) < sqrt;){
if(number % primes.get(index) == 0){
number += 2;
index = 0;
sqrt = (long)(Math.sqrt(number) + 1);
continue;
}
index ++;
}
primes.add(number);
number += 2;
}
int lineCount = 0;
for(int index = startIndex - 1; index < endIndex ; index ++){
System.out.print(primes.get(index));
lineCount ++;
System.out.print(lineCount % 10 == 0 ? "\n" : " ");
}
}
}