1059 Prime Factors (25point(s))
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^211171011291
#include<bits/stdc++.h>
using namespace std;
const int maxn=100010;
int prime[maxn];
bool hashTable[maxn]={
false};
struct factor{
int x,cnt;
}f[10];
int ans=0;
void find_prime(){
for(int i=2;i<maxn;++i){
if(!hashTable[i]) prime[ans++]=i;
for(int j=i+i;j<maxn;j+=i) hashTable[j]=true;
}
}
int main(){
find_prime();
int n;
cin>>n;
int backup=n;
int num=0;
for(int i=0;i<ans&&prime[i]*prime[i]<n;++i){
if(backup%prime[i]==0){
f[num].x=prime[i],f[num].cnt=0;
while(backup%prime[i]==0){
f[num].cnt++;
backup/=prime[i];
}
num++;
}
}
if(backup!=1){
f[num].x=backup;
f[num++].cnt=1;
}
cout<<n<<"=";
for(int i=0;i<num;++i){
if(i!=0) cout<<"*";
cout<<f[i].x;
if(f[i].cnt!=1) cout<<"^"<<f[i].cnt;
}
if(n==1) cout<<1;
cout<<endl;
}