a725簡單還原質因數表示再重新分解
CPE:Prime Land (UVa 516)
計算原整數減一後的降冪質因數表示。
解題思路
同一行中的數字兩兩配對為質數 p 與次方 e,先用整數乘法累乘 p 共 e 次,還原 x。輸入保證 x≤32767,因此不需要浮點 pow,也沒有大整數問題。再令 v=x−1。
依序試除 d=2,3,…,每次除盡 d 並記次數;當 d²>剩餘值即可停止,剩餘值若大於 1 就是最後的質因數。收集結果後反向輸出,符合質數遞減規則。逐行讀取才能識別每組配對,單獨 0 結束,數字間只放一個空白。
Step-by-step animation
示意:5¹×2¹=10
步驟 1 / 3
還原並減一
5×2=10,待分解數為 9。
5^1
2^1
9
- x
- 10
- v
- 9
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main() {
string line;
while (getline(cin, line)) {
istringstream in(line);
int p, e;
if (!(in >> p))
continue;
if (!p)
break;
int x = 1;
in >> e;
for (int i = 0; i < e; ++i)
x *= p;
while (in >> p >> e)
for (int i = 0; i < e; ++i)
x *= p;
int v = x - 1;
vector<pair<int, int>> f;
for (int d = 2; d * d <= v; ++d)
if (v % d == 0) {
int count = 0;
while (v % d == 0) {
v /= d;
++count;
}
f.push_back({d, count});
}
if (v > 1)
f.push_back({v, 1});
bool first = true;
for (auto it = f.rbegin(); it != f.rend(); ++it) {
if (!first)
cout << ' ';
first = false;
cout << it->first << ' ' << it->second;
}
cout << '\n';
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。