Skip to content

Instantly share code, notes, and snippets.

@Qqwy
Created August 8, 2016 18:42
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 Qqwy/8037cfdd28adad375f8df18fa25572c8 to your computer and use it in GitHub Desktop.
Save Qqwy/8037cfdd28adad375f8df18fa25572c8 to your computer and use it in GitHub Desktop.
defmodule Modulo do
defmacro guard_safe_int_max(a, b) do
quote do
div(unquote(a)+unquote(b) + abs(unquote(a) - unquote(b)), 2)
end
end
defmacro int_sign(x) do
quote do
div(unquote(x), guard_safe_int_max(abs(unquote(x)), 1))
end
end
defmacro floor_div(a, n) do
quote do
div(unquote(a), unquote(n)) + div(int_sign(rem(unquote(a), unquote(n)) * unquote(n)) - 1, 2)
end
end
defmacro mod(a, n) do
quote do
unquote(a) - (unquote(n) * floor_div(unquote(a), unquote(n)))
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment