Olympiad in Informatics

P1072: Hankson's Interesting Problem — Solution

A Super Concise Approach

After reading this solution I AC’d it right away. It really is a very concise approach.

We have \(gcd(x,a_0)=a_1\). By the result \(gcd(a,b)=c \to gcd(\frac{a}{c},\frac{b}{c})=1\), we can derive:

\[gcd(\frac{x}{a_1},\frac{a_0}{a_1})\]

The other equation, \(lcm(x,b_0)=b_1\), can be transformed into:

\[\begin{gathered} lcm(x,b_0)=b_1 \\ gcd(x,b_0)*lcm(x,b_0)=xb_0 \\ gcd(x,b_0)=\frac{xb_0}{b_1} \\ gcd(\frac{b_1}{b_0},\frac{b_1}{x})=1 \end{gathered}\]

We can see that \(x\) is a divisor of \(b_1\) and \(a_1\) is a divisor of \(x\). Using these two conditions and the two \(gcd\) conditions, just enumerate.

Code

// CH3201.cpp
#include <bits/stdc++.h>
using namespace std;
int n, a0, a1, b0, b1;
int gcd(int a, int b) { return (b == 0) ? a : gcd(b, a % b); }
int main()
{
    scanf("%d", &n);
    while (n--)
    {
        int ans = 0;
        scanf("%d%d%d%d", &a0, &a1, &b0, &b1);
        int p = b1 / b0, q = a0 / a1;
        for (int x = 1; x * x <= b1; x++)
            if (b1 % x == 0)
            {
                if (x % a1 == 0 && gcd(p, b1 / x) == 1 && gcd(q, x / a1) == 1)
                    ans++;
                int y = b1 / x;
                if (x == y)
                    continue;
                if (y % a1 == 0 && gcd(p, b1 / y) == 1 && gcd(q, y / a1) == 1)
                    ans++;
            }
        printf("%d\n", ans);
    }
    return 0;
}