# Solve congruence equation where unknown variable is in both sides of congruent operator

I am trying to solve the following equation:

$$(a*n + c) \mod (b-n) \equiv 0$$

and $$n$$ must be the lowest value in $$[0, b-1]$$

for example $$a=17$$, $$c=-59$$ and $$b=128$$, the solution is $$n=55$$

$$n=b-1$$ will be always a solution, because $$m \mod 1 \equiv 0$$

Equivalently, you want to solve in integers $$y (b-n) = an+c$$ This is equivalent to $$(y+a)(b-n) = ab+c$$ You want $$b-n$$ to be as large as possible subject to $$b-n \le b$$. Thus you want to factor $$ab+c$$ and take its largest divisor $$\le b$$. In your example, $$ab+c = 2117 = 29 \cdot 73$$ whose largest divisor $$\le 128$$ is $$73$$, so $$n = 128 - 73 = 55$$.