rloopsgreatest-common-divisorlcm

Create a function for Least Common Multiple for a vector in R with helper functions


In R, I have two helper functions

gcf(x,y) for finding the greatest common factor of two numbers

and

lcm(x,y) for finding the lease common multple of two numbers.

For example,

> gcd(85,75)
[1] 5
> lcm(20,50)
[1] 100

Now, I need to create a function that takes a vector of integers as the argument that returns the least common multiple for the elements.

for example,

lcm_vector(c(20,50,75)) = 300

I know that this will take calculation

LCM(20, 50, 75) = LCM(LCM(20, 50), 75).

But how do I work on the element of the vector? Do I need loops?


Solution

  • You can use Reduce to keep running lcm with each new value in the vector

    lcm_vector <- function(x) Reduce(lcm, x)
    lcm_vector(c(20,50,75))
    # [1] 300
    

    If you have a vector like x<-c(a,b,c,d,e) and you have function f. Calling Reduce(f, x) is like calling f(f(f(f(a, b), c), d), e)