From 57d48ed16ea6a4b419ee242a4800c8e62adf1fa7 Mon Sep 17 00:00:00 2001 From: Simon Waldherr Date: Tue, 29 Oct 2024 19:20:40 +0100 Subject: [PATCH] add common divisor and common multiple --- mathematics/greatest_common_divisor.r | 24 ++++++++++++++++++++++++ mathematics/least_common_multiple.r | 27 +++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 mathematics/greatest_common_divisor.r create mode 100644 mathematics/least_common_multiple.r diff --git a/mathematics/greatest_common_divisor.r b/mathematics/greatest_common_divisor.r new file mode 100644 index 00000000..9c2b94c1 --- /dev/null +++ b/mathematics/greatest_common_divisor.r @@ -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 diff --git a/mathematics/least_common_multiple.r b/mathematics/least_common_multiple.r new file mode 100644 index 00000000..d440f29c --- /dev/null +++ b/mathematics/least_common_multiple.r @@ -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