Fork me on GitHub

PAT(甲级)渡劫(十九)-Prime Factors(25)


PAT(甲级)渡劫(十九)-Prime Factors(25)

代码如下:

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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>
#include <cstdio>
#include <cmath>

const int maxn = 60000;
bool mark[maxn];
int prime[maxn];
int primeSize = 0;

void init(){
for(int i = 0 ; i < maxn ; i++){
mark[i] = false;
}
for(int i = 2 ; i < maxn ; i++){
if(mark[i] == true) continue;
prime[primeSize++] = i;
for(int j = 2*i ; j < maxn ; j += i)
mark[j] = true;
}
}

int main(){
freopen("in.txt","r",stdin);
int num;
init();
scanf("%d",&num);
if(num == 1){
printf("1=1");
return 0;
}
printf("%d=",num);
int ansPrime[maxn];
int ansSize = 0;
int ansNum[maxn];
for(int i = 0 ; i < primeSize ; i++){
if(num%prime[i] == 0){
ansPrime[ansSize] = prime[i];
ansNum[ansSize] = 0;
while(num%prime[i] == 0){
ansNum[ansSize]++;
num/=prime[i];
}
ansSize++;
if(num == 1) break;
}
}
if(num != 1){
ansPrime[ansSize] = num;
ansNum[ansSize++] = 1;
}

for(int i = 0 ; i < ansSize ; i++){
if(i != ansSize - 1){
if(ansNum[i] > 1){
printf("%d^%d*",ansPrime[i],ansNum[i]);
}else{
printf("%d*",ansPrime[i]);
}
}else{
if(ansNum[i] > 1){
printf("%d^%d",ansPrime[i],ansNum[i]);
}else{
printf("%d",ansPrime[i]);
}
}
}
return 0;
}

运行结果:

坚持原创技术分享,您的支持将鼓励我继续创作
-------------本文结束感谢您的阅读-------------
0%