Skip to content

Commit

Permalink
Add gcd and lcm functions (closes #3)
Browse files Browse the repository at this point in the history
  • Loading branch information
EllaKaye committed Jan 1, 2024
1 parent f48489a commit 06412d0
Show file tree
Hide file tree
Showing 4 changed files with 76 additions and 0 deletions.
2 changes: 2 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,5 @@ export(aoc_new_year)
export(aoc_url)
export(aoc_url_input)
export(extract_numbers)
export(gcd)
export(lcm)
31 changes: 31 additions & 0 deletions R/maths-helpers.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# function for greatest common divisor
# applies Euclid's algorithm
#' Greatest Common Divisor (GCD) and Least Common Multiple (LCM)
#'
#' @param x A single integer
#' @param y A single integer
#'
#' @return The greatest common divisor of x and y
#' @export
#'
#' @examples gcd(12, 18)
#' @examples gcd(12, 0)
#' @examples gcd(13, 2)
gcd <- function(x, y) {
while (y != 0) {
t <- y
y <- x %% y
x <- t
}
x
}


#' @rdname gcd
#' @export
#' @examples lcm(12, 18)
#' @examples lcm(2, 6)
#' @examples lcm(3, 5)
lcm <- function(x, y) {
x * y / gcd(x, y)
}
30 changes: 30 additions & 0 deletions man/gcd.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 13 additions & 0 deletions tests/testthat/test-maths-helpers.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# write tests for gcd
test_that("gcd works", {
expect_equal(gcd(12, 18), 6)
expect_equal(gcd(12, 0), 12)
expect_equal(gcd(13, 2), 1)
})

# write tests for lcm
test_that("lcm works", {
expect_equal(lcm(12, 18), 36)
expect_equal(lcm(2, 6), 6)
expect_equal(lcm(3, 5), 15)
})

0 comments on commit 06412d0

Please sign in to comment.