Reducing Integer Fractions Algorithm - Solution Explanation?

Posted by Andrew Tomazos - Fathomling on Stack Overflow See other posts from Stack Overflow or by Andrew Tomazos - Fathomling
Published on 2012-09-10T21:31:39Z Indexed on 2012/09/10 21:38 UTC
Read the original article Hit count: 239

Filed under:
|
|
|

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

© Stack Overflow or respective owner

Related posts about c++

Related posts about algorithm