PAT甲級1059 Prime Factors
阿新 • • 發佈:2019-01-01
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
- 題解:先建立一個一萬以內的素數表,然後再從第一個素數開始往後判斷是否為n的因子,並統計這個素因子出現的次數。注意特判 n == 1的情況。
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <map> #include <vector> #define ll long long using namespace std; map<ll, int> mp; vector<ll> v; void Prime(ll n){ mp.clear(); for(ll i = 2; i <= 10000; i++){ if(mp[i] == 1) continue; v.push_back(i);//i是素數 for(ll j = i; j <= 10000/i; j++){ mp[i*j] = 1; } } } int main() { ll n, cnt = 0; scanf("%lld", &n); if(n == 1){//特例 printf("1=1\n"); return 0; } Prime(n); printf("%lld=", n); int flag = 0;//flag用於標記是否是第一個素因子,用於輸出格式的控制 for(int i = 0; i < v.size(); i++){ cnt = 0; if(n % v[i] == 0){ if(flag) printf("*%lld", v[i]); else printf("%lld", v[i]); flag = 1; while(n % v[i] == 0){ n /= v[i]; cnt++; } if(cnt > 1){//該素因子個數大於1則輸出指數 printf("^%lld", cnt); } } } printf("\n"); return 0; }