From d7f80c6f45563ff390bafad2ef5d34346449f70f Mon Sep 17 00:00:00 2001 From: pthomalla Date: Sun, 25 Nov 2018 15:44:58 +0100 Subject: [PATCH 1/2] fix modulo --- lib/math/math.ex | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/lib/math/math.ex b/lib/math/math.ex index c04dc67..6add982 100644 --- a/lib/math/math.ex +++ b/lib/math/math.ex @@ -19,10 +19,17 @@ defmodule ExthCrypto.Math do iex> ExthCrypto.Math.mod(0, 1337) 0 + + iex> ExthCrypto.Math.mod(-75, 32) + 21 """ - def mod(x, n) when x > 0, do: rem x, n - def mod(x, n) when x < 0, do: rem n + x, n - def mod(0, _n), do: 0 + def mod(x, n) do + remainder = rem(x, n) + + if remainder < 0, + do: n + remainder, + else: remainder + end @doc """ Simple wrapper function to convert a hex string to a binary. @@ -108,4 +115,4 @@ defmodule ExthCrypto.Math do :crypto.exor(a, b) end -end \ No newline at end of file +end From e47c4e2652d192ead4bea7a18e8085113d730e90 Mon Sep 17 00:00:00 2001 From: pthomalla Date: Wed, 28 Nov 2018 10:05:12 +0100 Subject: [PATCH 2/2] divisor can be negative --- lib/math/math.ex | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/math/math.ex b/lib/math/math.ex index 6add982..7f5b879 100644 --- a/lib/math/math.ex +++ b/lib/math/math.ex @@ -22,11 +22,17 @@ defmodule ExthCrypto.Math do iex> ExthCrypto.Math.mod(-75, 32) 21 + + iex> ExthCrypto.Math.mod(75, -32) + -21 + + iex> ExthCrypto.Math.mod(-10,-3) + -1 """ def mod(x, n) do remainder = rem(x, n) - if remainder < 0, + if (remainder < 0 and n > 0) or (remainder > 0 and n < 0), do: n + remainder, else: remainder end