题目
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.
Sample Input:
97532468
Sample Output:
97532468=2^2*11*17*101*1291
即求质因数分解,
由小向大扫描,依次取余判断,如果有相应的质因数项,考虑系数。
注意,输入可能是1,输入可能是质数。
代码:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
long p[65]; //存质因子
int k[65]={0}; //存系数
long n; //输入的数
cin>>n;
cout<<n<<"=";
if(n==1) //!!!输入可能为1
{
cout<<1;
return 0;
}
long i=0; //记录非重复质因子数量
long j=2;
int flag=0; //获得质因子标志位,用于重新计算sqr
long sqr=sqrt((double)n)+1; //求根,计算质因子时需要的上界
while(n>1)
{
if(flag==1) //重新计算上界
{
sqr=sqrt((double)n)+1;
flag=0;
}
for(;j<=sqr;j++) //从上次的位置开始扫描
{
if(n%j==0) //扫描到一个
{
p[i]=j; //记录
k[i]=1;
n/=j;
while(n%j==0) //获取系数
{
n/=j;
k[i]++;
}
i++; //刷新数据,为扫描下一个做准备
j++;
flag=1;
break;
}
}
if(j>sqr) //超界,意味着本身是质数
{
p[i]=n;
k[i]=1;
i++;
break;
}
}
if(k[0]==1) //输出
cout<<p[0];
else
cout<<p[0]<<"^"<<k[0];
for(j=1;j<i;j++)
{
if(k[j]==1)
cout<<"*"<<p[j];
else
cout<<"*"<<p[j]<<"^"<<k[j];
}
return 0;
}