I am going for a full range (+ and -) x, y
answer with no int
overflow and clearly determine when no solution is possible.
Given:
1 <= k <= n
k % x == y
k % x == y
implies
k = quotient * x + y
where quotient
is some integer.
When x == 0
, then
any_int % 0
is not defined, so in C we cannot certainly form an answer.
1 <= n
is also required in all cases.
if (x == 0 || n < 1) No_solution;
When x > 0
, then
y >= 0
(positive_int % x is never < 0)
and
y < x
(positive_int % x is always < x
).
With k % x == y
and 1 <= k <= n
, then
n >= y
must be true for a solution.
if (x > 0 && (y < 0 || y >= x || y > n)) No_solution;
After rejecting above no solution combinations:
quotient * x + y <= n // leads to ...
quotient <= (n-y)/x // quotient is >= 0 and overflow not possible
largest_k = (n-y)/x * x + y // largest_k >= 0 and overflow not possible
if (largest_k == 0) No_solution;
When x < 0
, then
y >= 0
(positive_int % x is never < 0)
and
y < -x
(positive_int % x is always < -x
).*1
(Recall a%b
is not a mod b
when negatives values are involved.
if (x < 0 && (y < 0 || y > -1 - x || y > n)) No_solution;
The rest of the analysis follows the x > 0
case, except quotient <= 0
All together
if (x == 0 || n < 1 || y < 0 || y > n) return No_solution;
if (x > 0 && y >= x) return No_solution;
if (x < 0 && y > -1 - x) return No_solution;
int quotient = (n-y)/x;
int largest_k = quotient * x + y;
if (largest_k == 0) return No_solution;
printf("Largest k: %d\n", largest_k);
// I suspect simplifications possible - maybe later.
*1
y < -x
could be re-written as y <= -1 - x
. This form handles all negative x
including INT_MIN
.