[Learning Record] Linear Congruence Inequality

Consider the solution L ≤ D x mod M ≤ RL\le Dx \bmod M \le RLDxmodMR,其中 0 ≤ L ≤ R < M , D < M 0 \le L \le R < M, D < M 0LR<M,D<M

Suppose there is a solution, then there is yyy, 使得L ≤ D x - M y ≤ ML \ le Dx -My \ le MLDxMyM . Deformed to get
D x − R ≤ M y ≤ D x − L Dx-R\le My \le Dx-LDxRMyDxL

To DDD 取模,得到
− R   m o d   D ≤ ( M   m o d   D ) y   m o d   D ≤ − L   m o d   D -R \bmod D \le (M \bmod D) y \bmod D\le -L \bmod D RmodD(MmodD)ymodDLmodD

So it becomes a smaller form, which can be recursed according to this form. The complexity is the same as the division method, which is O (log ⁡ n) O(\log n)O(logn ) . The solution obtained in this way is the smallest non-negative integer solution.

As for why the solution after such a transformation must be the same as the original question, and why the solution must be the smallest, I have not found a convincing answer.

Take POJ 3530 as an example, give the realization:

ll modinq(ll m, ll d, ll l, ll r){
    
    
    // 0 <= l <= r < m, d < m, minimal non-negative solution
    if (r < l) return -1;
    if (l == 0) return 0;
    if (d == 0) return -1;
    if ((r / d) * d >= l) return (l - 1) / d + 1;
    ll res = modinq(d, m % d, (d - r % d) % d, (d - l % d) % d);
    return res == -1 ? -1: (m * res + l - 1) / d + 1;
}

Guess you like

Origin blog.csdn.net/zqy1018/article/details/108780838