PAT 1059. Prime Factors (25) 质因子分解

题目链接 http://www.patest.cn/contests/pat-a-practise/1059

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 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.(坑爹,这最后一句不是说满足情况不输出,可答案是要输出的,害我吓考虑2个case没过)

Sample Input:

97532468

Sample Output:

97532468=2^2*11*17*101*1291
---------------------------------------------------华丽的分割线---------------------------------------------------------------------------------------------
 1 #include <iostream>
 2 #include <cmath>
 3 using namespace std;
 4 const int maxn=100005;
 5 int prime[maxn],pnum=0;
 6 bool p[maxn]={0};
 7 void Find_Prime(){
 8     p[0]=p[1]=true;
 9     for(int i=2;i<maxn;i++){
10         if(p[i]==false){
11             prime[pnum++]=i;
12             for(int j=i+i;j<maxn;j+=i)
13                 p[j]=true;
14         }
15     }
16 }
17 struct factor{
18     int x,cnt;
19 }fac[20];
20 int num;
21 void PrimeFactor(int n){
22     int sqr=(int)sqrt(n);
23     num=0;
24     for(int i=0;i<maxn && prime[i]<=sqr;i++){
25         if(n%prime[i]==0){
26             fac[num].x=prime[i];
27             fac[num].cnt=0;
28             while(n%prime[i]==0){
29                 fac[num].cnt++;
30                 n/=prime[i];
31             }
32             num++;
33         }
34         if(n==1) break;
35     }
36     if(n!=1){
37         fac[num].x=n;
38         fac[num++].cnt=1;
39     }
40 }
41 void Print_fac(int n){
42     printf("%d=",n);
43     for(int i=0;i<num;i++){
44         if(i>0)
45             printf("*");
46         if(fac[i].cnt>1)
47             printf("%d^%d",fac[i].x,fac[i].cnt);
48         else
49             printf("%d",fac[i].x);
50     }
51     printf("
");
52 }
53 int main()
54 {
55     Find_Prime();
56     int n;
57     while(scanf("%d",&n)!=EOF){
58         if(n==1)
59             printf("1=1
");
60         else{
61             PrimeFactor(n);
62             Print_fac(n);
63         }
64 
65         /*
66         int a=(1<<31)-1;
67         cout<<a<<endl;
68         cout<<"1"<<endl;
69         PrimeFactor(a);
70         cout<<"2"<<endl;
71         Print_fac(a);
72         cout<<"3"<<endl;
73         cout<<num<<endl;
74         */
75     }
76     return 0;
77 }
78 //97532468=2^2*11*17*101*1291
原文地址:https://www.cnblogs.com/johnleo/p/Prime_factor.html