Official

G - Ai + Bj + Ck = X (1 <= i, j, k <= N) Editorial by en_translator


Since \(N \le 10^6\), one can exhaustively iterate \(i\). Then, the problem is boiled down to \(Bj+Ck=Y\) (where \(Y=X-Ai\)).

This Diophantine equation can be solved with the extended Euclidean algorithm (extgcd).

Specifically, one can use extgcd to find a solution satisfying \(Bj+Ck=\gcd(B,C)\); multiplying it by a constant, one can find a solution where the right hand side is \(Y\%B\). (Conversely, if such a solution cannot be obtained, there is no solution for the current \(i\).)
Then, one can adjust \(j\) to find the solution of the original Diophantine equation.

The general solution is in the form of \(j'=j+tC/\gcd(B,C), k'=k-tB/\gcd(B,C)\) (where \(t\) is an integer). One can count the number of \(t\) where the unknowns are between \(1\) and \(N\) to count the solutions of the original Diophantine equation.

posted:
last update: