某次參加CPE時的題目,當時出在第五題,我沒有解出來,有夠哭。
## 題目
[點我](https://onlinejudge.org/external/1/160.pdf)
## 題意
給定n,算出n階乘,但要將它質因數分解。
舉例來說,n=5,n! = 120 = 2 ^ <font color="#f00">3</font> + 3 ^ <font color="#f00">1</font> + 5 ^ <font color="#f00">1</font>
因此輸出5! = 3 1 1
2 <= n <= 100
## 演算法
> 建質數表,用來做質因數分解,建到100以內就好,因為n最大到100。

> 這是用來存答案的陣列

>主函式

>function,第四行有誤,應為i /= prime[idx]

題目不難,主要是輸出格式很麻煩,可以參考以下的程式碼。
## 程式碼
```cpp=
#include <bits/stdc++.h>
using namespace std;
void prime_factorization(int prime[] , int prime_number[] , int i){
int prime_idx = 0;
while(i != 1){
while(i % prime[prime_idx] == 0){
i /= prime[prime_idx];
prime_number[prime[prime_idx]]++;
}
prime_idx++;
}
}
int main(){
int n;
while(1){
cin >> n;
if(n == 0) break;
//less than 100 prime
int prime[25] = {2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 , 43 , 47 , 53 , 59 , 61 , 67 , 71 , 73 , 79 , 83 , 89 , 97};
int prime_number[100] = {};
for(int i = 2 ; i <= n ; i++){
prime_factorization(prime , prime_number , i);
}
int last = 24;
while(prime_number[prime[last]] == 0) last--;
cout << setw(3)<< n << "!" << " =";
if(last < 15){
for(int i = 0 ; i <= last ; i++){
cout << setw(3) << prime_number[prime[i]];
}
cout << endl;
}
else{
for(int i = 0 ; i < 15 ; i++){
cout << setw(3) << prime_number[prime[i]];
}
cout << endl;
cout << " ";
for(int i = 15 , j = 0 ; j <= last % 15 ; j++){
cout << setw(3) << prime_number[prime[i + j]];
}
cout << endl;
}
}
return 0;
}
```
## 我寫code時犯的錯誤
無窮迴圈,因為pseudocode寫錯,邏輯錯誤。
固定寬度,格式錯誤。
輸出格式,格式錯誤。
100以內的質數打錯,失誤。
## 後記
寫題目花了一個小時,輸出格式也弄了一個小時,怒。