Skip to content

Instantly share code, notes, and snippets.

@geohot
Last active March 4, 2023 06:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geohot/acd5b2b4a622b1427247bc7b619f1f13 to your computer and use it in GitHub Desktop.
Save geohot/acd5b2b4a622b1427247bc7b619f1f13 to your computer and use it in GitHub Desktop.
mod of a range
# given a number in the range [amin, amax] (inclusive)
# what are the min and max of that number after modding it by b?
# c style modulus
def modn(a, b): return -((-a)%b) if a < 0 else a%b
# aka a fast version of
def slow_modrange(amin, amax, b):
values = [modn(rv, b) for rv in range(amin, amax+1)]
return min(values), max(values)
# ...long answer relegated to history...
# or, if you like short. with help from the tinygrad discord:
def fast_modrange(amin, amax, b):
if amin < 0 and amax >= 0: return (max(-b+1, amin), min(amax, b-1))
m1, m2 = modn(amin, b), modn(amax, b)
if amax - amin >= b or (m1 >= m2 and amin != amax): return (0, b-1) if amin >= 0 else (-b+1, 0)
return m1, m2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment