PAT (Advanced Level) Practice 1059 Prime Factors (25 minutes) [mathematics: prime]

Given any positive integer N N , you are supposed to find all of its prime factors, and write them in the format N = p 1 k 1 × p 2 k 2 × × p m k m N=p_1^{k_1}×p_2^{k_2}×⋯×p_m^{k_m} .

Input Specification:

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

Output Specification:

Factor N in the format N N = p 1 p_1 ^ k 1 k_1 * p 2 p_2 ^ k 2 k_2 * * p m p_m ^ k m k_m , where p i p_i 's are prime factors of N N in increasing order, and the exponent k i k_i is the number of p i p_i – hence when there is only one p i p_i , k i k_i is 1 and must NOT be printed out.

Sample Input:

97532468

Sample Output:

97532468=2^2*11*17*101*1291

The meaning of problems

Number will be a prime factor decomposition.

Thinking

First, to calculate the prime numbers, range of data in question is long int, that is, 2 3 2 2^32 . due to 2 1 6 = 65536 2^16=65536 , only to all prime numbers within the calculated required 100,000. After obtaining these prime numbers are prime numbers divisible removal of x, until x = 1.

Possible after all the prime numbers are still not in addition to x 1, x this time is a big prime numbers. But the data is weak, do not consider this situation could go.

Note that the boundary where x = 1.

Code

#include <iostream>

using namespace std;
#define MAX_N 100000

bool not_prime[MAX_N];

int main() {
    int x;
    cin >> x;
    cout << x << "=";
    if (x == 1)
        cout << "1";

    for (int i = 2; i < MAX_N; ++i)  // 欧拉筛
        if (!not_prime[i])
            for (int j = i + i; not_prime[j / i]; j += i)
                not_prime[j] = true;

    bool first = true;
    for (int i = 2; i < MAX_N && x != 1; ++i) {
        if (!not_prime[i]) {
            int cnt = 0;
            while (x % i == 0) {
                x /= i;
                ++cnt;
            }
            if (cnt > 0) {
                if (first)
                    first = false;
                else
                    cout << '*';
                cout << i;
                if (cnt > 1)
                    cout << '^' << cnt;
            }
        }
    }
    if (x != 1)
        cout << '*' << x;
}

Published 184 original articles · won praise 19 · views 20000 +

Guess you like

Origin blog.csdn.net/Exupery_/article/details/104167812