1059 Prime Factors (25分)
Given any positive integer NNN, you are supposed to find all of its prime factors, and write them in the format NNN = p1k1×p2k2×⋯×pmkm{p_1}^{k_1}\times {p_2}^{k_2} \times \cdots \times {p_m}^{k_m}p1k1×p2k2×⋯×pmkm.
Input Specification:
Each input file contains one test case which gives a positive integer NNN in the range of long int.
Output Specification:
Factor NNN in the format NNN =
p1p_1p1^
k1k_1k1*
p2p_2p2^
k2k_2k2*
…*
pmp_mpm^
kmk_mkm, where pip_ipi's are prime factors of NNN in increasing order, and the exponent kik_iki is the number of pip_ipi -- hence when there is only one pip_ipi, kik_iki is 1 and must NOT be printed out.
Sample Input:
97532468
Sample Output:
97532468=2^2*11*17*101*1291
给定一个正整数,求它的质因子分解。先利用素数打表获取质数,然后判断是否是其因子。利用结构体factor存储质因子。
参考代码:
#include <cstdio>
#include <cmath>
#include <cstring>
const int maxn=100010;
struct factor{
int x,cnt; //x为质因子,cnt为数目
}fac[10];
int pri[100010] ,pnum;
bool p[maxn];
void findprime(int n)
{
for(int i=2;i<maxn;++i)
{
if(p[i]==false)
{
pri[pnum++]=i;
for(int j=i+i;j<maxn;j+=i)
{
p[j]=true;
}
}
}
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
memset(p,0,sizeof(p));
pnum=0;
findprime(n);
int count=0;
if(n==1)
printf("1=1\n"); //特判1
else
{
printf("%d=",n);
int sqr=(int)sqrt(1.0*n);
for(int i=0;i<pnum&&pri[i]<=sqr;++i)
{
if(n%pri[i]==0)
{
fac[count].x=pri[i];
fac[count].cnt=0;
while(n%pri[i]==0)
{
fac[count].cnt++;
n/=pri[i];
}
count++;
}
if(n==1)
break;
}
if(n!=1)
{
fac[count].x=n;
fac[count].cnt=1;
count++;
}
for(int i=0;i<count;++i)
{
if(i>0)
printf("*");
printf("%d",fac[i].x);
if(fac[i].cnt>1)
printf("^%d",fac[i].cnt);
}
printf("\n");
}
}
return 0;
}