Skip to content

Commit

Permalink
Add euclidean function and test
Browse files Browse the repository at this point in the history
  • Loading branch information
fyradur committed Sep 24, 2024
1 parent 7ef0153 commit 5296f29
Show file tree
Hide file tree
Showing 5 changed files with 65 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .Rbuildignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
^\.github$
^.*\.Rproj$
^\.Rproj\.user$
23 changes: 23 additions & 0 deletions R/euclidean.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#' The Euclidean algorithm
#'
#' The algorithm takes two numeric scalars and applies the Euclidean
#' algorithm to it. In the case these two numeric scalars are
#' integers the greatest common divisor is yielded.
#'
#' A description with pseudocode can be found at the Wikipedia page here:
#' https://en.wikipedia.org/wiki/Euclidean_algorithm.

#'
#' @param x A numeric scalar
#' @param y A numeric scalar
#' @return The Euclidean algorithm on x and y. For the case of two integers, the GCD is yielded.


euclidean <- function(x,y){
# Stop if any argument isn't a numeric scalar
stopifnot(is.numeric(x), length(x) == 1)
stopifnot(is.numeric(y), length(y) == 1)

if (y == 0){x}
else {euclidean(y,x %% y)}
}
25 changes: 25 additions & 0 deletions man/euclidean.Rd

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

12 changes: 12 additions & 0 deletions tests/testthat/test_euclidean.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
test_that("GDC is calculated correctly.", {
expect_equal(euclidean(123612, 13892347912), 4)
expect_equal(euclidean(100, 1000), 100)
expect_equal(euclidean(-100, 1000), 100)
})


test_that("Wrong input throws an error.", {
expect_error(euclidean("100", 1000))
expect_error(euclidean(100, "1000"))
expect_error(euclidean(TRUE, "1000"))
})
3 changes: 3 additions & 0 deletions twofamousalgorithms/R/twofamousalgorithms-package.R
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,8 @@
#' The algorithm takes a graph and an initial node and calculates the shortest
#' path from the initial node to every other node in the graph.
#'
#' @section euclidean:
#' Takes two numeric scalars and applies the euclidean algorithm to them. In the case
#' of two integers the greatest common divisor is yielded.


0 comments on commit 5296f29

Please sign in to comment.