This is a followup to this problem:
Reducing Integer Fractions Algorithm
Following is a solution to the problem from a grandmaster:
#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;
}
It isn’t clear to me how it works. Can anyone explain it?
The equivilance is as follows:
a is the numerator vector of length n
b is the denominator vector of length m
initsimply fills the arrayPso thatP[i]contains the largest prime factor ofi.f(n,a,x)fillsxwith the number of times a number in a is divisible by each prime, counting powers multiple times. In effect it computers the prime factorization of the product ofa.g(v,w)takes a list of numbersvand a prime factorizationwand divides out any element in v with a common factor in w until they share no common factors. (Dividing the prime factorization means subtracting the power by 1).So now we have
main. First it initializes theParray and reads in the data lengths (strangely it never appears to read in the data itself). Then it stores the prime factorizations of the products of elements in a and b in x and y respectively. Then it uses a lambda expression in a loop to take the element wise minimum of these two factorizations, giving the factorization of the greatest common factor. Finally it divides out elements in a and b by this common factor.