Least Multiple 1:20 - How Can I Do It Faster?

I am trying to find the smallest number that evenly divides 1:20. I created a function, and this is what I have:

smallestN<- function(a,b) {
  i<- 1
  repeat {
     if (all(i%%a:b == 0)) {
      break
    } else {
      i<-i+1
    }
  }
  return(i)
}

It works great for short intervals, but for 1:20 it takes a lot of time. How can I improve my code to make it faster?

+4
source share
1 answer

I think you're after the least common option . There are several ways to calculate this, but first you can see the packagenumbers

library(numbers)

mLCM(1:20)
# [1] 232792560

There will be faster implementations that use C/C++, but for the script, 1:20this is fast.

+5
source

Source: https://habr.com/ru/post/1687839/


All Articles