1059 Prime Factors (25 point(s))
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
经验总结:
emmmm 经典的质因子分解方法, 注意一下N等于1时的处理,求质数表使用埃氏筛法即可~~
AC代码
#include <cstdio>
#include <cmath>
const int maxn=100010;
int flag[maxn]={false},prime[maxn],pNum=0;
void find_prime()
{
flag[0]=flag[1]=true;
for(int i=2;i<maxn;++i)
{
if(flag[i]==false)
{
prime[pNum++]=i;
for(int j=i+i;j<maxn;j+=i)
{
flag[j]=true;
}
}
}
}
struct factor
{
int cnt;
int x;
}fac[10];
int main()
{
int n;
scanf("%d",&n);
find_prime();
if(n==1)
printf("%d=%d\n",n,n);
else
{
printf("%d=",n);
int num=0;
int sqr=(int)sqrt(n*1.0);
for(int i=0;prime[i]<=sqr;++i)
{
if(n%prime[i]==0)
{
fac[num].x=prime[i];
fac[num].cnt=0;
while(n%prime[i]==0)
{
++fac[num].cnt;
n/=prime[i];
}
++num;
}
}
if(n!=1)
{
fac[num].x=n;
fac[num++].cnt=1;
}
if(fac[0].cnt==1)
printf("%d",fac[0].x);
else
printf("%d^%d",fac[0].x,fac[0].cnt);
for(int i=1;i<num;++i)
{
if(fac[i].cnt==1)
printf("*%d",fac[i].x);
else
printf("*%d^%d",fac[i].x,fac[i].cnt);
}
printf("\n");
}
return 0;
}