Skip to content

Commit

Permalink
Merge pull request #11 from sotolf2/main
Browse files Browse the repository at this point in the history
Implemented euclidian modulo
  • Loading branch information
NicklasXYZ committed Jan 23, 2024
2 parents 449eac6 + 8c2471a commit 0c01501
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
50 changes: 50 additions & 0 deletions src/gleam_community/maths/arithmetics.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,56 @@ fn do_gcd(x: Int, y: Int) -> Int {
}
}

/// <div style="text-align: right;">
/// <a href="https://github.com/gleam-community/maths/issues">
/// <small>Spot a typo? Open an issue!</small>
/// </a>
/// </div>
///
/// 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
///
///
/// <details>
/// <summary>Example:</summary>
///
/// 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)
/// }
/// </details>
///
/// <div style="text-align: right;">
/// <a href="#">
/// <small>Back to top ↑</small>
/// </a>
/// </div>
///
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
}
}

/// <div style="text-align: right;">
/// <a href="https://github.com/gleam-community/maths/issues">
/// <small>Spot a typo? Open an issue!</small>
Expand Down
11 changes: 11 additions & 0 deletions test/gleam_community/maths/arithmetics_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 0c01501

Please sign in to comment.