wrap-around icon indicating copy to clipboard operation
wrap-around copied to clipboard

Devise a more elegant formula for handling negative numbers

Open semibran opened this issue 8 years ago • 4 comments
trafficstars

Currently using (n % m + m) % m which looks hideously overcomplicated. sure it passes tests, but there's gotta be a better way of doing it?

semibran avatar Jun 27 '17 07:06 semibran

What's wrong with doing Math.abs(n % m)?

hannawalter avatar Sep 13 '19 22:09 hannawalter

incidentally this is what i tried first; see this section of the readme - abs(n % m) yields incorrect output e.g. f(-4) -> 1 instead of 2

semibran avatar Sep 13 '19 22:09 semibran

haha. 7 years later. here's mine: some magic numbers but it works: ((n + 1) % m) + m - 1

n % m this provides numbers in the range [-m+1, 0]. ((n) % m) + (m - 1) adding (m-1) puts them in the expected range [0,m] AND in the expected order, but off by 1. ((n + 1) % m) + m - 1 replacing n with n + 1 accounts for the offset

hedgewizards avatar Jan 20 '23 07:01 hedgewizards

Good thing 1 isn't a magic number 🙂 Sacrifices a bit of readability to get the order of ops right but I guess it is one less modulo. If you put a PR up I can patch it through

semibran avatar Jan 20 '23 19:01 semibran