1. 程式人生 > >PAT-BASIC1013——數素數

PAT-BASIC1013——數素數

題目描述:

知識點:素數

思路:記錄索引在M-N間的素數,格式化輸出

本題提供的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解題報告: