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

时间:2024-08-13 23:33:56

题目链接 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
---------------------------------------------------华丽的分割线---------------------------------------------------------------------------------------------
 #include <iostream>
#include <cmath>
using namespace std;
const int maxn=;
int prime[maxn],pnum=;
bool p[maxn]={};
void Find_Prime(){
p[]=p[]=true;
for(int i=;i<maxn;i++){
if(p[i]==false){
prime[pnum++]=i;
for(int j=i+i;j<maxn;j+=i)
p[j]=true;
}
}
}
struct factor{
int x,cnt;
}fac[];
int num;
void PrimeFactor(int n){
int sqr=(int)sqrt(n);
num=;
for(int i=;i<maxn && prime[i]<=sqr;i++){
if(n%prime[i]==){
fac[num].x=prime[i];
fac[num].cnt=;
while(n%prime[i]==){
fac[num].cnt++;
n/=prime[i];
}
num++;
}
if(n==) break;
}
if(n!=){
fac[num].x=n;
fac[num++].cnt=;
}
}
void Print_fac(int n){
printf("%d=",n);
for(int i=;i<num;i++){
if(i>)
printf("*");
if(fac[i].cnt>)
printf("%d^%d",fac[i].x,fac[i].cnt);
else
printf("%d",fac[i].x);
}
printf("\n");
}
int main()
{
Find_Prime();
int n;
while(scanf("%d",&n)!=EOF){
if(n==)
printf("1=1\n");
else{
PrimeFactor(n);
Print_fac(n);
} /*
int a=(1<<31)-1;
cout<<a<<endl;
cout<<"1"<<endl;
PrimeFactor(a);
cout<<"2"<<endl;
Print_fac(a);
cout<<"3"<<endl;
cout<<num<<endl;
*/
}
return ;
}
//97532468=2^2*11*17*101*1291