How to find the least common multiple of a range of numbers?

前端 未结 14 1700
一个人的身影
一个人的身影 2020-12-08 08:32

Given an array of two numbers, let them define the start and end of a range of numbers. For example, [2,6] means the range 2,3,4,5,6. I want to write javascrip

14条回答
  •  爱一瞬间的悲伤
    2020-12-08 08:43

    As this question has recently been revived, here's what I think is a simpler take on the question, writing very simple helper functions to calculate the greatest common divisor of two integers (gcd), to calculate the least common multiple of two integers (lcm), to calculate the least common multiple of an array of integers (lcmAll), to generate the range of integers between two given integers (rng), and finally, in our main function, to calculate the least common multiple of the range of integers between two given integers (lcmRng):

    const gcd = (a, b) => b == 0 ? a : gcd (b, a % b)
    const lcm = (a, b) =>  a / gcd (a, b) * b
    const lcmAll = (ns) => ns .reduce (lcm, 1)
    const rng = (lo, hi) => [...Array (hi - lo + 1)] .map ((_, i) => lo + i)
    
    const lcmRng = (lo, hi) => lcmAll (rng (lo, hi))
    
    console .log (lcmRng (1, 13))

    All of these functions are simple. Although the question was tagged recursion, only gcdis recursive. If this is an attempt to play with recursion, we could rewrite lcmAll in a recursive manner with something like this:

    const lcmAll = (ns) => 
      ns.length == 0 
        ? 1 
        : lcm(ns[0], lcmAll(ns .slice (1)))
    

    Although I'm a big fan of recursion, I see no other reason to choose the recursive version here over the reduce one. In this case, reduce is cleaner.

    And finally, if you really want the API originally requested where the range bounds are passed in an array, you could write one more wrapper:

    const leastCommonMultiple = ([lo, hi]) => lcmRng (lo, hi)
    
    leastCommonMultiple ([1, 13]) //=> 360360
    

提交回复
热议问题