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
可参考柳神:https://blog.csdn.net/liuchuo/article/details/52261852
另解:
#include<cstdio>
#include<cmath>
using namespace std;
const int maxn=100001;
bool isPrime(int n){
if(n==1) return false;
for(int i=2;i*i<=n;i++){
if(n%i==0) return false;
}
return true;
}
int prime[maxn],pnum=0;
void findPrime(){
for(int i=1;i<maxn;i++){
if(isPrime(i)==true)
prime[pnum++]=i;
}
}
struct factor{
int a,ans;
}fac[10];
int main(){
findPrime();
int n,num=0;
scanf("%d",&n);
if(n==1) printf("1=1");
else {
printf("%d=",n);
int sqr=(int)sqrt(1.0*n);
for(int i=0;i<pnum&&i<=sqr;i++){
if(n%prime[i]==0){
fac[num].a=prime[i];
fac[num].ans=0;
while(n%prime[i]==0){
fac[num].ans++;
n=n/prime[i];
}
num++;
}
if(n==1) break;
}
if(n!=1) {
fac[num].a=n;
fac[num].ans=1;
}
for(int i=0;i<num;i++){
if(i>0) printf("*");
printf("%d",fac[i].a) ;
if(fac[i].ans>1) printf("^%d",fac[i].ans );
}
}
return 0;
}