Last active
March 4, 2023 06:33
-
-
Save geohot/acd5b2b4a622b1427247bc7b619f1f13 to your computer and use it in GitHub Desktop.
mod of a range
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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