Skip to content

Commit

Permalink
Add common divisor and common multiple (#135)
Browse files Browse the repository at this point in the history
  • Loading branch information
SimonWaldherr authored Oct 29, 2024
1 parent acbb8d8 commit ad2f096
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
24 changes: 24 additions & 0 deletions mathematics/greatest_common_divisor.r
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# GCD Calculation using Euclidean Algorithm
find_gcd <- function(a, b) {

#' @description Computes the Greatest Common Divisor (GCD) of two integers.
#' @param a Integer
#' @param b Integer
#' @usage find_gcd(a, b)
#' @details This function uses the Euclidean algorithm to find the GCD.
#' GCD is essential in various mathematical contexts, particularly in
#' simplification of fractions and number theory applications.
#' @references https://en.wikipedia.org/wiki/Euclidean_algorithm

while (b != 0) {
temp <- b
b <- a %% b
a <- temp
}

return(abs(a))
}

# Examples
print(find_gcd(48, 18)) # expected 6
print(find_gcd(54, 24)) # expected 6
27 changes: 27 additions & 0 deletions mathematics/least_common_multiple.r
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# LCM Calculation
find_lcm <- function(a, b) {

#' @description Computes the Least Common Multiple (LCM) of two integers.
#' @param a Integer
#' @param b Integer
#' @usage find_lcm(a, b)
#' @details This function uses the relationship between GCD and LCM,
#' i.e., LCM(a, b) = |a * b| / GCD(a, b).
#' LCM is useful in fraction operations and periodicity calculations.
#' @references https://en.wikipedia.org/wiki/Least_common_multiple

gcd <- function(x, y) {
while (y != 0) {
temp <- y
y <- x %% y
x <- temp
}
return(abs(x))
}

return(abs(a * b) / gcd(a, b))
}

# Examples
print(find_lcm(48, 18)) # expected 144
print(find_lcm(54, 24)) # expected 216

0 comments on commit ad2f096

Please sign in to comment.