PAT 甲级 1059 Prime Factors

https://pintia.cn/problem-sets/994805342720868352/problems/994805415005503488

 

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 = 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

代码:

#include <bits/stdc++.h>
using namespace std;

long int P;
int prime[500010];

int main() {
    memset(prime, 1, sizeof(prime));
    for(int i = 2; i * i <= 500010; i ++)
        for(int j = 2; j * i < 500010; j ++)
        prime[j * i] = 0;
    scanf("%ld", &P);

    printf("%ld=", P);
    if(P == 1) printf("1");

    bool First = false;
    for(int i = 2; P >= 2; i ++) {
        int cnt = 0, flag = 0;
        while(prime[i] && P % i == 0) {
            cnt ++;
            P /= i;
            flag = 1;
        }
        if(flag) {
            if(First)
                printf("*");
            printf("%d", i);
            First = true;
        }
        if(cnt > 1)
            printf("^%d", cnt);
    }
    return 0;
}

  素数表! Get

posted @ 2018-12-27 16:51  丧心病狂工科女  阅读(227)  评论(0编辑  收藏  举报