Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Devise a more elegant formula for handling negative numbers #1

Open
semibran opened this issue Jun 27, 2017 · 4 comments
Open

Devise a more elegant formula for handling negative numbers #1

semibran opened this issue Jun 27, 2017 · 4 comments

Comments

@semibran
Copy link
Owner

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?

@hannawalter
Copy link

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

@semibran
Copy link
Owner Author

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

@hedgewizards
Copy link

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

@semibran
Copy link
Owner Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants