-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add gcd and lcm functions (closes #3)
- Loading branch information
Showing
4 changed files
with
76 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -14,3 +14,5 @@ export(aoc_new_year) | |
export(aoc_url) | ||
export(aoc_url_input) | ||
export(extract_numbers) | ||
export(gcd) | ||
export(lcm) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
}) |