PAT甲級真題 1059 Prime Factors (25分) C++實現(建立素數備忘錄)

題目

Given any positive integer N, you are supposed to find all of its prime factors, and write them in the format N = p1^k1 * p2^k2 *…*pm^km.

Input Specification:

Each input file contains one test case which gives a positive integer N in the range of long int.

Output Specification:

Factor N in the format N = p1^k1 * p2^k2 *…*pm^km, where pi’s are prime factors of N in increasing order, and the exponent ki is the number of pi – hence when there is only one pi, ki is 1 and must NOT be printed out.

Sample Input:
97532468
Sample Output:
97532468=2^2*11*17*101*1291

思路

爲了避免重複運算,維護一個素數表prime,初始化爲{2}。

分解N時,先考察素數表中的數是否是其因子;若素數表中沒有其因子,且素數表中最大值比根N小,那麼逐個考察到根N,每發現一個素數都保存到素數表中。

把N的因子m保存到factor數組中,再迭代考察n / m;若其沒有因子,則其本身就是素數,將其保存到factor中。

最後按指定規則輸出結果即可。

注意輸入的值可能是1,需單獨考慮,否則測試點3無法通過。

代碼

#include <iostream>
#include <cmath>
#include <vector>
using namespace std;

vector<int> prime;  //素數備忘錄
vector<int> factor;  //素因數
bool isPrime(int n){
    for (int i=2; i<=sqrt(n); i++){
        if (n % i == 0){
            return false;
        }
    }
    return true;
}
void divide(int n){
    if (n < 2){
        return;
    }
    int len = prime.size();
    int m = 0;
    for (int i=0; i<len; i++){
        if (n % prime[i] == 0) {
            m = n / prime[i];
            factor.push_back(prime[i]);
            break;
        }
    }
    if (m==0){  //n不能被備忘錄中的素數整除,繼續考察根N範圍內是否有因數,擴展素數備忘錄
        for (int i=prime[len-1]+1; i<=sqrt(n); i++){
            if (isPrime(i)){
                prime.push_back(i);
                if (n % i == 0){
                    m = n / i;
                    factor.push_back(i);
                    break;
                }
            }
        }
    }
    if (m==0){  //n確定是素數
        factor.push_back(n);
        return;
    }
    else {
        divide(m);
    }
}
int main(){
    prime.push_back(2);
    int n;
    cin >> n;
    cout << n << "=";
    if (n==1){
        cout << "1";
    }
    else{
        divide(n);
        int i = 0;
        while (i<factor.size()){
            if (i > 0){
                cout << "*";
            }
            cout << factor[i];
            int j = i + 1;
            while (j<factor.size() && factor[j]==factor[i]){
                j++;
            }
            int k = j - i;
            if (k > 1){
                cout << "^" << k;
            }
            i = j;
        }
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章