Official

C - Max GCD 2 Editorial by en_translator


The number of possible pairs \((x, y)\) are at most \(2 \times 10^{10}\), so we cannot calculate \(\gcd\) for every pair \((x, y)\). Instead, let us fix the answer \(c\), and consider the yes-no problem “does there exist a pair \((x, y)\) such that \(\gcd(x, y) = c\)?”

Since it’s the greatest common divisor, \(x\) and \(y\) should both be multiples of \(c\). Conversely, if there are two ore more multiples of \(c\) in the segment \([A, B]\), then one can choose \((x, y)\) such that \(\gcd(x, y)\) (by choosing the consecutive multiples of \(c\)).

Since \(B ≤ 2 \times 10^5\), for each \(c = 1, 2, \dots, B\), one can check if the segment \([A, B]\) contains two or more multiples of \(c\), so that the original problem is solved fast enough.


The number of multiples of \(c\) between \(A\) and \(B\) (hereinafter inclusive) can be calculated as:
(the number of multiples of \(c\) between \(A\) and \(B\)) = (the number of multiples of \(c\) between \(1\) and \(B\)) - (the number of multiples of \(c\) between \(1\) and \(A-1\)) \({}=\left\lfloor\dfrac Bc\right\rfloor - \left\lfloor\dfrac {A - 1}c\right\rfloor\).

Otherwise, since it is sufficient to check if there are at least two of them, we can check it by \(\left\lceil\dfrac Ac\right\rceil < \left\lfloor\dfrac Bc\right\rfloor\).

Sample Code (C++)

#include <iostream>
using namespace std;

int main(){
    int A, B;
    cin >> A >> B;
    for(int c = B; ; c--) if((A + c - 1) / c < B / c){
        cout << c << endl;
        return 0;
    }
}

Sample Code (Python)

A, B = map(int, input().split())
for c in range(B, 0, -1):
    if (A + c - 1) // c < B // c:
        exit(print(c))

posted:
last update: