我的PAT-BASIC代码仓:https://github.com/617076674/PAT-BASIC
原题链接:https://pintia.cn/problem-sets/994805260223102976/problems/994805309963354112
题目描述:
知识点:素数
思路:记录索引在M-N间的素数,格式化输出
对于素数的判断,和PAT-BASIC1007——素数对猜想是同样的思路。
本题提供的JAVA代码能够获得通过,但有时会超时。
C++代码:
#include<iostream>
#include<math.h>
#include<vector>
using namespace std;
bool isPrime(int num);
int main() {
int m;
int n;
cin >> m >> n;
int count = 1;
vector<int> primes;
for (int i = 2; ; i++) {
if (isPrime(i)) {
if (count >= m) {
primes.push_back(i);
}
if (count >= n) {
break;
}
count++;
}
}
for (int i = 0; i < primes.size(); i++) {
if ((i + 1) % 10 == 0) {
printf("%d\n", primes[i]);
} else {
if (i == primes.size() - 1) {
printf("%d", primes[i]);
} else {
printf("%d ", primes[i]);
}
}
}
}
bool isPrime(int num) {
for (int i = 2; i <= sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
C++解题报告:
JAVA代码:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int m = scanner.nextInt();
int n = scanner.nextInt();
ArrayList<Integer> arrayList = new ArrayList<>();
int index = 1;
for (int i = 2; ; i++) {
if(isPrime(i)){
if(index >= m){
arrayList.add(i);
}
if(index == n){
break;
}
index++;
}
}
for (int i = 0; i < arrayList.size(); i++) {
System.out.print(arrayList.get(i));
if(i != arrayList.size() - 1) {
if ((i + 1) % 10 == 0) {
System.out.println();
} else {
System.out.print(" ");
}
}
}
}
private static boolean isPrime(int num){
for (int i = 2; i <= Math.sqrt(num); i++) {
if(num % i == 0){
return false;
}
}
return true;
}
}
JAVA解题报告: