#46072: 用map結構的普通解法


s724123 (愛玉)

學校 : 國立聯合大學
編號 : 309428
來源 : [111.83.38.104]
最後登入時間 :
2025-05-18 09:18:22

//適當使用資料結構可以讓程式更清晰
#include <iostream>
#include <map>
using namespace std;
map<int, int> factorization(int n) {
map<int, int> factors;
if (n <= 1) {
return factors;
}
while (n % 2 == 0) {
        factors[2]++;
        n /= 2;
}
for (int i = 3; i * i <= n; i += 2) {
while (n % i == 0) {
factors[i]++;
n /= i;
}
}
if (n > 2) {
factors[n]++;
}
return factors;
}
int main()
{
int n;
cin >> n;
    map<int, int> factors = factorization(n);
bool first = true;
for (auto factor : factors) {                              //auto是自動推導類型,本來是pair<const int,int>
if (!first) {
cout << " * ";
}
if (factor.second > 1) {
cout << factor.first << "^" << factor.second; 
}
else {
cout << factor.first;
}
first = false;
}
}