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.
题目分析: 首先 2*3*5*7*11*13*17*19*23*29,最小的十个质因数相乘就已经超出了 int 的范围,所以 int 范围的整数最多可分解成十个不同的质因子。所以 fac 数组开到 10 就行。
先把素数表打印出来,因为是 int 范围,所以素数表打印到 1e5 就行。
注意:因为 1 不是素数,当 n==1 时,需要特判输出 "1=1".
代码如下:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
using namespace std;
const int maxn=1e5;
bool isprime[maxn];
int prime[maxn],nprime=0;
void doprime()///素数打表
{
long long i,j;
memset(isprime,true,sizeof(isprime));
isprime[1]=false;
for(i=2;i<=maxn;i++)
if(isprime[i])
{
prime[++nprime]=i;
for(j=i*i;j<=maxn;j+=i)
isprime[j]=false;
}
}
struct factor///结构体存放质因子及其个数
{
int x;
int cnt;
}fac[10];
int main()
{
doprime();
int n;
int num=0;///n为不同的质因子的个数(质因子的数量)
scanf("%d",&n);
if(n==1) printf("1=1");
else
{
printf("%d=",n);
int sqr=(int)sqrt(double(n));
for(int i=1;i<=nprime&&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;
num++;
}
for(int i=0;i<num;i++)///注意输出的格式
{
if(i>0) printf("*");
printf("%d",fac[i].x);
if(fac[i].cnt>1)
printf("^%d",fac[i].cnt);
}
}
return 0;
}