Search code examples
rgreatest-common-divisorlcm

How do I create a function for finding the Least Common Multiple of a vector of integers using Greatest Common Factor in R?


Suppose I have a function gcf(x,y) that returns the greatest common factor of x and y. So, for example,

gcf(75,85) = 5

Now, I'm trying to create a function lcm(v) that takes a vector of integers and returns the least common multiple.

I know mathematically it will be

lcd(a,b) = a*b/((gcf(a,b))

But I have a vector as the argument. How do I start writing the code? Also, how do I make sure that the vector has at least two integers and no more than 100?


Solution

  • 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.