Skip to content

Commit ad2f096

Browse files
Add common divisor and common multiple (#135)
1 parent acbb8d8 commit ad2f096

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

mathematics/greatest_common_divisor.r

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# GCD Calculation using Euclidean Algorithm
2+
find_gcd <- function(a, b) {
3+
4+
#' @description Computes the Greatest Common Divisor (GCD) of two integers.
5+
#' @param a Integer
6+
#' @param b Integer
7+
#' @usage find_gcd(a, b)
8+
#' @details This function uses the Euclidean algorithm to find the GCD.
9+
#' GCD is essential in various mathematical contexts, particularly in
10+
#' simplification of fractions and number theory applications.
11+
#' @references https://en.wikipedia.org/wiki/Euclidean_algorithm
12+
13+
while (b != 0) {
14+
temp <- b
15+
b <- a %% b
16+
a <- temp
17+
}
18+
19+
return(abs(a))
20+
}
21+
22+
# Examples
23+
print(find_gcd(48, 18)) # expected 6
24+
print(find_gcd(54, 24)) # expected 6

mathematics/least_common_multiple.r

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# LCM Calculation
2+
find_lcm <- function(a, b) {
3+
4+
#' @description Computes the Least Common Multiple (LCM) of two integers.
5+
#' @param a Integer
6+
#' @param b Integer
7+
#' @usage find_lcm(a, b)
8+
#' @details This function uses the relationship between GCD and LCM,
9+
#' i.e., LCM(a, b) = |a * b| / GCD(a, b).
10+
#' LCM is useful in fraction operations and periodicity calculations.
11+
#' @references https://en.wikipedia.org/wiki/Least_common_multiple
12+
13+
gcd <- function(x, y) {
14+
while (y != 0) {
15+
temp <- y
16+
y <- x %% y
17+
x <- temp
18+
}
19+
return(abs(x))
20+
}
21+
22+
return(abs(a * b) / gcd(a, b))
23+
}
24+
25+
# Examples
26+
print(find_lcm(48, 18)) # expected 144
27+
print(find_lcm(54, 24)) # expected 216

0 commit comments

Comments
 (0)