这是这个问题的后续:
Reducing Integer Fractions Algorithm
以下是大师对问题的解答:
#include <cstdio>
#include <algorithm>
#include <functional>
using namespace std;
const int MAXN = 100100;
const int MAXP = 10001000;
int p[MAXP];
void init() {
for (int i = 2; i < MAXP; ++i) {
if (p[i] == 0) {
for (int j = i; j < MAXP; j += i) {
p[j] = i;
}
}
}
}
void f(int n, vector<int>& a, vector<int>& x) {
a.resize(n);
vector<int>(MAXP, 0).swap(x);
for (int i = 0; i < n; ++i) {
scanf("%d", &a[i]);
for (int j = a[i]; j > 1; j /= p[j]) {
++x[p[j]];
}
}
}
void g(const vector<int>& v, vector<int> w) {
for (int i: v) {
for (int j = i; j > 1; j /= p[j]) {
if (w[p[j]] > 0) {
--w[p[j]];
i /= p[j];
}
}
printf("%d ", i);
}
puts("");
}
int main() {
int n, m;
vector<int> a, b, x, y, z;
init();
scanf("%d%d", &n, &m);
f(n, a, x);
f(m, b, y);
printf("%d %d\n", n, m);
transform(x.begin(), x.end(), y.begin(),
insert_iterator<vector<int> >(z, z.end()),
[](int a, int b) { return min(a, b); });
g(a, z);
g(b, z);
return 0;
}
我不清楚它是如何工作的。谁能解释一下?
等价关系如下:
a is the numerator vector of length n
b is the denominator vector of length m
最佳答案
init
简单地填充数组 P
以便 P[i]
包含 i
的最大质因数.
f(n,a,x)
将 a 中的数字被每个质数整除的次数填充到 x
中,计算多次幂。实际上,它计算了 a
的乘积的质因数分解。
g(v,w)
获取一个数字列表 v
和一个质因数分解 w
并将 v 中的任何元素除以 a w 中的公因数,直到它们没有公因数。 (除以质因数分解就是乘方减1)。
现在我们有了main
。首先它初始化 P
数组并读入数据长度(奇怪的是它似乎从来没有读入过数据本身)。然后它将a和b中元素的乘积的质因数分解分别存储在x和y中。然后它在循环中使用 lambda 表达式来获取这两个因式分解的元素最小值,给出最大公因数的因式分解。最后,它通过这个公因数划分 a 和 b 中的元素。
关于c++ - 减少整数分数算法 - 解决方案解释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12359785/