Problem Description
Problem Analysis
It is easy to think of the extended Euclidean algorithm.
From the problem statement we get
Convert it into $a\cdot x+b\cdot y=gcd\left( a,b\right)$
Then
Therefore we can determine whether gcd(m-n,-L) divides (y-x)
Since L must be greater than 0
So write the equation as $\left( n-m\right) t+k\cdot L=x-y$
Use the extended Euclidean algorithm to find x and y
The rest can be used to find t
Then consider the case t<0
Quote a solution:
Theorem 1: If d =gcd(a, b), then there must exist integers k and l, positive or negative, such that d = ax+ by.
Theorem 2: If gcd(a,b) = 1, then the equation ax ≡ c (mod b) has a unique solution in [0, b-1].
Theorem 3: If gcd(a,b) = d, then the equation ax ≡ c (mod b) has a unique solution in [0, b/d - 1].
Proof: The above congruence equation is equivalent to ax + by = c. If it has a solution, dividing both sides by d gives a/d * x + b/d * y = c/d, i.e. a/d * x ≡ c/d (modb/d). Clearly gcd(a/d, b/d) = 1, so by Theorem 2 we know x has a unique solution in [0, b/d - 1]. Therefore the x in ax + by = c has a unique solution in [0, b/d - 1], i.e. ax ≡ c (mod b) has a unique solution in [0, b/d - 1].
If a particular solution X of ax ≡ c (mod b) is obtained, then let r = b/gcd(a, b). We know x has a unique solution in [0, r-1], so x = (x% r + r) % r gives the smallest non-negative integer solution x! (X % r may be negative; in that case it stays within [-(r-1), 0], while a positive value stays within [0, r-1]. Adding r keeps it within [1, 2r - 1], so taking the modulus by r again puts it within [0, r-1]).
| |
Recommended article: POJ 1061 Frog’s Date - w446506278’s Blog