diff --git a/src/gleam_community/maths/arithmetics.gleam b/src/gleam_community/maths/arithmetics.gleam index 9d1c018..acb0fd1 100644 --- a/src/gleam_community/maths/arithmetics.gleam +++ b/src/gleam_community/maths/arithmetics.gleam @@ -96,6 +96,56 @@ fn do_gcd(x: Int, y: Int) -> Int { } } +///
+/// +/// Spot a typo? Open an issue! +/// +///
+/// +/// The function calculates the Euclidian modulo of two numbers +/// The Euclidian_modulo is the modulo that most often is used in maths +/// rather than the normal truncating modulo operation that is used most +/// often in programming through the % operator +/// In contrast to the % operator this function will always return a positive +/// result +/// +/// Like the gleam division operator / this will return 0 if one of the +/// parameters are 0 as this is not defined in mathematics +/// +/// +///
+/// Example: +/// +/// import gleeunit/should +/// import gleam_community/maths/arithmetics +/// +/// pub fn example() { +/// arithmetics.euclidian_modulo(15, 4) +/// |> should.equal(3) +/// +/// arithmetics.euclidian_modulo(-3, -2) +/// |> should.equal(1) +/// +/// arithmetics.euclidian_modulo(5, 0) +/// |> should.equal(0) +/// } +///
+/// +///
+/// +/// Back to top ↑ +/// +///
+/// +pub fn euclidian_modulo(x: Int, y: Int) -> Int { + case x % y, x, y { + _, 0, _ -> 0 + _, _, 0 -> 0 + md, _, _ if md < 0 -> md + int.absolute_value(y) + md, _, _ -> md + } +} + ///
/// /// Spot a typo? Open an issue! diff --git a/test/gleam_community/maths/arithmetics_test.gleam b/test/gleam_community/maths/arithmetics_test.gleam index 57e6753..104cb4d 100644 --- a/test/gleam_community/maths/arithmetics_test.gleam +++ b/test/gleam_community/maths/arithmetics_test.gleam @@ -21,6 +21,17 @@ pub fn int_gcd_test() { |> should.equal(6) } +pub fn euclidian_modulo_test() { + arithmetics.euclidian_modulo(15, 4) + |> should.equal(3) + + arithmetics.euclidian_modulo(-3, -2) + |> should.equal(1) + + arithmetics.euclidian_modulo(5, 0) + |> should.equal(0) +} + pub fn int_lcm_test() { arithmetics.lcm(1, 1) |> should.equal(1)