No need to reinvent the wheel. You can try the package library(pracma)
and the vectorized functions gcd
& Lcm
like
a1 = c(75, 30)
b1 = c(85, 10)
pracma::gcd(a1,b1)
[1] 5 10
pracma::Lcm(a1,b1)
[1] 1275 30
Check View(pracma::gcd)
or hit F2
in RStudio to learn from the source code. The second question is a typical if statement:
foo <- function(x, y){
require(pracma)
if(length(x) < 2 | length(x) > 100 ) return("Length of x must be at least 2 and not more than 100")
if(length(y) < 2 | length(y) > 100 ) return("Length of y must be at least 2 and not more than 100")
list(gcd=pracma::gcd(x,y),
lcm=pracma::Lcm(x,y))
}
foo(a1, b1)
$gcd
[1] 5 10
$lcm
[1] 1275 30
Edit
As you commented you want to find the least common factor of three or more numbers. Thus, you can start and play with the following lines of code e.g. for a vector of length of six. The idea is to test all combinations of length 2 and finally reduce them from left to right.
a =c(21, 45, 3 , 90, 72, 99)
combn(a, 2, simplify = F) %>%
map(~gcd(.[1], .[2])) %>%
Reduce(function(x,y) gcd(x, y),.)
But without any guarantee for correctness of the result.