Alex
Alex

Reputation: 7688

Javascript recursive function within a loop

I can't seem to move on from the: RangeError: Maximum call stack size exceeded error. 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.

Pretty much ran out of ideas. Any suggestions please?

Upvotes: 0

Views: 138

Answers (1)

ASDFGerte
ASDFGerte

Reputation: 5195

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. This means that when your original smallest is not divisible by 19, you produced an endless recursion.

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

Upvotes: 1

Related Questions