Solving $ax \equiv c \pmod b$ efficiently when $a,b$ are not coprime

I know how to compute modular multiplicative inverses for co-prime variables $a$ and $b$, but is there an efficient method for computing variable $x$ where $x < b$ and $a$ and $b$ are not co-prime, given variables $a$, $b$ and $c$, as described by the equation below?

$ a x \equiv c \mod b $

For example, given

$ 154x \equiv 14 \mod 182 $, is there an efficient method for computing all the possibilities of $x$, without pure bruteforce?

Please note that I'm not necessarily asking for a direct solution, just a more optimized one.

I do not believe that the Extended Euclidean Algorithm will work here, because $a$ and $b$ are not co-prime.

Edit: Follow up question, since the first one had a shortcut:

Could the be computed efficiently as well?

$12260x \equiv 24560 \mod 24755$.

$107$ needs to be one of the computed answers.


Solving $154x \equiv 14 \pmod{182}$ is the same as finding all solutions to $$ 154x + 182y = 14.$$ In this case, we might think of this as finding all solutions to $$14(11x + 13y) = 14(1),$$ or rather $$11x + 13 y = 1.$$ Finally, solving this is the same as solving $11x \equiv 1 \pmod {13}$, which has solution $x \equiv 6 \pmod{13}$.

So we learn that $x \equiv 6 \pmod{13}$ is the solution. Of course, this isn't a single residue class mod $182$. Thinking modulo $182$, we see that the solutions are $x \equiv 6, 6+13,6+26,6+39, \ldots, 6+13*13 \equiv 6, 19, 32, \ldots, 175.$

This approach works generally --- factor out the greatest common divisor, consider the resulting modular problem, and then bring it back up to the original problem.


To solve $ax\equiv c \mod b$, set $\;d=a\wedge b$, $\;a=a'd, \;b=b'd$. This congruence implies $c$ is divisible by $d$. Actually, it's easy to see that $$ax\equiv c\mod b\iff \begin{cases}c\equiv 0\mod a\wedge b\\\text{and}\\a'x\equiv c'=\dfrac{c}{a\wedge b} \mod b' \end{cases}$$ Thus the problem comes down to the case $a$ and $b$ coprime, after a compatibility condition has been checked.

Added: solution of the second congruence

First we check with the Euclidean algorithm that $\gcd(12260,24755)=5$, and $$\frac{12260}5=2452,\quad\frac{24755}5=4951,\quad\frac{24560}5=4912. $$ Thus the given congruence is equivalent to $ \; 2452 x\equiv 4912\mod 4951$, and we have to find the inverse of $2452$ modulo $4951$. This means we have to find a *Bézout's relation between $2452$ and $4951$. It can be obtained with the extended Euclidean algorithm: $$\begin{array}{rrrr} r_i&u_i&v_i&q_i\\ \hline 4951&0&1\\ 2452&1&0&2\\\hline 47&-2&1&52\\ 8&105&-52&5\\ 7&-527&261&1\\ 1&632&-313\\\hline \end{array}$$ Thus $632\cdot2452-313\cdot4951=1$, whence $2452^{-1}=632\bmod4951$, and the solution is $$x\equiv 632\cdot4912\equiv 107\mod4951.$$