gpt4 book ai didi

math - 计算两个区间的模

转载 作者:行者123 更新时间:2023-12-01 03:40:47 25 4
gpt4 key购买 nike

我想了解模数运算符在应用于两个区间时是如何工作的。在代码中实现两个区间的加、减和乘法很简单,但是如何实现模数呢?

如果有人可以向我展示公式、示例代码或解释其工作原理的链接,我会很高兴。

背景信息:你有两个整数 x_lo < x < x_hiy_lo < y < y_hi . mod(x, y)的上下限是多少?

编辑:我不确定是否有可能以有效的方式提出最小界限(无需计算所有 x 或所有 y 的 mod)。如果是这样,那么我会接受一个准确但非最佳的边界答案。显然, [-inf,+inf] 是正确的答案 :) 但我想要一个大小更有限的边界。

最佳答案

事实证明,这是一个有趣的问题。 假设 我做的是为整数 区间,模是关于 定义的截断除法 (向 0 舍入)。

因此,mod(-a,m) == -mod(a,m)对于所有 a, m。此外,sign(mod(a,m)) == sign(a) .

定义,在我们开始之前

从 a 到 b 的闭区间: [a,b] 空区间: [] := [+Inf,-Inf] 否定: -[a,b] := [-b,-a] 工会: [a,b] u [c,d] := [min(a,c),max(b,d)] 绝对值: |m| := max(m,-m)
更简单的案例:固定模数 m
从固定的 m 开始更容易.我们稍后会将其推广到两个区间的模。定义建立递归 .用你最喜欢的编程语言来实现它应该没有问题。伪代码:

def mod1([a,b], m):
// (1): empty interval
if a > b || m == 0:
return []
// (2): compute modulo with positive interval and negate
else if b < 0:
return -mod1([-b,-a], m)
// (3): split into negative and non-negative interval, compute and join
else if a < 0:
return mod1([a,-1], m) u mod1([0,b], m)
// (4): there is no k > 0 such that a < k*m <= b
else if b-a < |m| && a % m <= b % m:
return [a % m, b % m]
// (5): we can't do better than that
else
return [0,|m|-1]

到目前为止,我们不能做得比这更好。 (5) 中的结果区间可能是过度近似,但这是我们能得到的最好结果。如果允许我们返回一组间隔,我们可以更精确。

一般情况

同样的想法适用于我们的模数本身就是一个区间的情况。开始了:
def mod2([a,b], [m,n]):
// (1): empty interval
if a > b || m > n:
return []
// (2): compute modulo with positive interval and negate
else if b < 0:
return -mod2([-b,-a], [m,n])
// (3): split into negative and non-negative interval, compute, and join
else if a < 0:
return mod2([a,-1], [m,n]) u mod2([0,b], [m,n])
// (4): use the simpler function from before
else if m == n:
return mod1([a,b], m)
// (5): use only non-negative m and n
else if n <= 0:
return mod2([a,b], [-n,-m])
// (6): similar to (5), make modulus non-negative
else if m <= 0:
return mod2([a,b], [1, max(-m,n)])
// (7): compare to (4) in mod1, check b-a < |modulus|
else if b-a >= n:
return [0,n-1]
// (8): similar to (7), split interval, compute, and join
else if b-a >= m:
return [0, b-a-1] u mod2([a,b], [b-a+1,n])
// (9): modulo has no effect
else if m > b:
return [a,b]
// (10): there is some overlapping of [a,b] and [n,m]
else if n > b:
return [0,b]
// (11): either compute all possibilities and join, or be imprecise
else:
return [0,n-1] // imprecise

玩得开心! :)

关于math - 计算两个区间的模,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31057473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com