我正在寻找一个完整的(+ 和 -)x, y 答案,没有 int 溢出,并清楚地确定什么时候没有解决方案是可能的。
鉴于:
1 <= k <= n
k % x == y
k % x == y暗示
k = quotient * x + y 其中quotient 是某个整数。
当x == 0, 然后
any_int % 0 未定义,因此在 C 中我们不能确定地形成答案。
1 <= n 在所有情况下也是必需的。
if (x == 0 || n < 1) No_solution;
当x > 0, 然后
y >= 0(positive_int % x is never < 0) 和
y < x(positive_int % x is always < x)。
使用k % x == y和1 <= k <= n,然后
对于解决方案,n >= y 必须为真。
if (x > 0 && (y < 0 || y >= x || y > n)) No_solution;
上面拒绝后没有解决方案组合:
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;
当x < 0, 然后
y >= 0(positive_int % x is never < 0) 和
y < -x(positive_int % x is always < -x)。*1
(当涉及负值时,回想一下a%b是nota mod b。
if (x < 0 && (y < 0 || y > -1 - x || y > n)) No_solution;
其余分析遵循x > 0案例,除了quotient <= 0
全部一起
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
", largest_k);
*1y < -x 可以重写为 y <= -1 - x。此表单处理所有负 xincludingINT_MIN`。