令P~i~表示第i个素数。现任给两个正整数M <= N <= 10^4^,请输出P~M~到P~N~的所有素数。
输入格式:
输入在一行中给出M和N,其间以空格分隔。
输出格式:
输出从P~M~到P~N~的所有素数,每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
一种java解法
import java.util.Scanner;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int from = scan.nextInt();
int to = scan.nextInt();
ArrayList<Integer> arr = generatearr(to);
int num = 0;
for(int i = from - 1; i < to; i++)
{
num++;
System.out.print(arr.get(i));
if(num == to - from + 1) continue;
else if(num % 10 == 0) System.out.print("\n");
else System.out.print(" ");
}
}
private static ArrayList<Integer> generatearr(int n)
{
ArrayList<Integer> result = new ArrayList<Integer>();
while(result.size() < n)
{
if(result.isEmpty()) result.add(2);
Integer newPrime = result.get(result.size() - 1) + 1;
for(int i = 0; i < result.size(); i++)
{
if(newPrime % result.get(i) == 0)
{
newPrime++;
i = -1;
continue;
}
}
result.add(newPrime);
}
return result;
}
}
由于时间限制是200ms,测试通过的时间大部分为150ms。有一个测试用例超时,因此改用C++解法如下:
#include<iostream>
#include<vector>
using namespace std;
vector<int> ge(int n)
{
vector<int> result;
while (result.size() < n)
{
if (result.size() == 0) result.push_back(2);
int newPrime = result.back() + 1;
for (int i = 0; i < result.size(); i++)
{
if (newPrime < result.at(i) * result.at(i)) break;
if (newPrime % result.at(i) == 0)
{
newPrime++;
i = -1;
continue;
}
}
result.push_back(newPrime);
}
return result;
}
int main()
{
int from, to;
cin >> from >> to;
vector<int> arr = ge(to);
int num = 0;
for (int i = from - 1; i < to; i++)
{
num++;
if (num == to - from + 1) { printf("%d", arr.at(i)); }
else if (num % 10 == 0) { printf("%d\n", arr.at(i)); }
else printf("%d ", arr.at(i));
}
}
注意生成素数的方法的效率,否则也有可能超时