简体   繁体   English

循环内的Javascript递归函数

[英]Javascript recursive function within a loop

I can't seem to move on from the: RangeError: Maximum call stack size exceeded error. 我似乎无法继续前进: RangeError: Maximum call stack size exceeded错误。 I am trying to find the smallest number that is evenly divisible by all numbers within a range. 我正在尝试找到可被范围内所有数字均分的最小数字。 The numbers in that range are passed on to the function as an array. 该范围内的数字作为数组传递给函数。

function smallestNumberEvenlyDivisible(smallest, numbers) {
    var z = 0;

    for (z; z < numbers.length; z++) {
        if (smallest % numbers[z] !== 0) {
            smallest += smallest;
            return smallestNumberEvenlyDivisible(smallest, numbers);
        }
    }

    return smallest;
}

smallestNumberEvenlyDivisible(2018940, [18, 19, 20, 21, 22, 23]);

I expect the output to be: 6056820 but obviously is not, because of the stack error. 我希望输出为: 6056820但显然不是,因为堆栈错误。

Pretty much ran out of ideas. 想法几乎用光了。 Any suggestions please? 有什么建议吗?

19 can never devide 2^n where n is natural because the only prime factor in 19 is itself and the only one is 2^n is 2 . 19永远不能将2^n ,因为n19唯一的素数是本身,而唯一的素数是2^n2 This means that when your original smallest is not divisible by 19 , you produced an endless recursion. 这意味着当您的原始smallest不能被19整除时,您将产生无穷递归。

I didn't do these things in a while and am not sure whether there are faster methods, but the smallest should be the multiplication of the minimal set that contains all prime factors of all the numbers. 我有一段时间没有做这些事情,也不知道是否有更快的方法,但是最小的应该是包含所有数字的所有素数的最小集的乘法。

In the example, 在这个例子中

  • 18 = 2 * 3 * 3
  • 19 = 19
  • 20 = 2 * 2 * 5
  • 21 = 3 * 7
  • 22 = 2 * 11
  • 23 = 23

Minimal number that will be devided by all numbers: 2 * 2 * 3 * 3 * 5 * 7 * 11 * 19 * 23 = 6056820 as you expected. 最小数字将由所有数字表示: 2 * 2 * 3 * 3 * 5 * 7 * 11 * 19 * 23 = 6056820如您2 * 2 * 3 * 3 * 5 * 7 * 11 * 19 * 23 = 6056820 How to algorithmically find prime factors should be easy to find. 如何通过算法找到主要因素应该很容易找到。

Note again that there are likely faster methods, perhaps what you intended to implement without the error you made? 再次注意,可能有更快的方法,也许您打算在没有错误的情况下实现?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM