pat a1059 prime factors

题目A1059 Prime Factors

Given any positive integer N, you are supposed to find all of its prime factors, and write them in the format $N = p_1^{k_1} times p_2^{k_2} times ⋯ times p_m^{k_m}​$.

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 = p_1^{k_1} times p_2^{k_2} times ⋯ times p_m^{k_m}$, where pi’s are prime factors of $N$ in increasing order, and the exponent $k_i$ is the number of $p_i$ — hence when there is only one $p_i$, $k_i$ is $1$ and must NOT be printed out.

Sample Input:

1
97532468

Sample Output:

1
97532468=2^2*11*17*101*1291

题意

  对数$N$分解质因数

思路

  可以先将素数表打出来,然后逐个进行除并记录个数,直到数$N$为1。这样做虽然$AC$了,但是当$N$为一个很大的素数时,并不会包含在表内。这时候我想到的就是遍历对$N$除去它的因子,直到$N$为质数或1。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

#include<string.h>
#include<algorithm>
using namespace std;
const int maxn=1e6+10;
int prime[maxn+1];
void ()
{
memset(prime,0,sizeof(prime));
for(int i=2;i<=maxn;i++)
{
if(!prime[i]) prime[++prime[0]]=i;
for(int j=1;j<=prime[0]&&prime[j]<=maxn/i;j++)
{
prime[prime[j]*i]=1;
if(i%prime[j]==0) break;
}
}
}
long long n;
int main()
{
init();
scanf("%lld",&n);
if(n==1) {printf("1=1n"); return 0;}
printf("%lld=",n);
bool flag=0;
for(int i=2;n>=2;i++)
{
int cnt=0;
while(prime[i]&&n%i==0)
{
n=n/i;
cnt++;
}
if(cnt)
{
if(flag) printf("*");
else flag=1;
if(cnt==1) printf("%d",i);
else printf("%d^%d",i,cnt);
}
}
return 0;
}