PAT 甲级 1059 Prime Factors

时间:2023-03-09 05:50:08
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 = 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 in the range of long int.

Output Specification:

Factor N in the format N = p​1​​^k​1​​*p​2​​^k​2​​**p​m​​^k​m​​, where p​i​​'s are prime factors of N in increasing order, and the exponent k​i​​ is the number of p​i​​ -- hence when there is only one p​i​​, k​i​​ 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