PAT Advanced 1059 Prime Factors (25分)
Given any positive integer N, you are supposed to find all of its prime factors, and write them in the format N = p1k1×p2k2×⋯×pmkm.
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
这道题我们用素数表存储500000个素数,进行筛选。
之后我们进行计数即可。
我们要注意的是格式化,以及1这个情况,否则会打印1=,实际上应该1=1
#include <iostream> #include <vector> #include <map> #define M 500000 using namespace std; vector<bool> v(M, 1); // prime table map<int, int> m; int main() { int N; scanf("%d", &N); printf("%d=", N); if(N == 1) printf("1"); for(int i = 2; i * i < M; i++) for(int j = 2; j * i < M; j++) v[i * j] = 0; for(int i = 2; i < M && N != 1; i++) { while(v[i] && N % i == 0 && N != 1) { m[i]++; N /= i; } } bool start = true; for(auto it = m.begin(); it != m.end(); it++) { if(it->second >= 1) { if(!start) printf("*"); if(it->second == 1) printf("%d", it->first); if(it->second > 1) printf("%d^%d", it->first, it->second); start = false; } }return 0; }