0

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?

Alex
  • 7,538
  • 23
  • 84
  • 152
  • 2
    Are you guaranteed to eventually hit a divisible number by continually doubling? – StephenTG Sep 12 '16 at 15:14
  • 1
    I think you are expecting to add 2018940 3 times but instead it's doubling each time, from 4037880 to 8075760. As a hint I think I know this problem and I'd recommend a different approach. – jeff carey Sep 12 '16 at 15:16
  • Your algorithm is flawed. Are you maybe looking for this: http://stackoverflow.com/questions/147515/least-common-multiple-for-3-or-more-numbers ? – Blaž Zupančič Sep 12 '16 at 15:19

1 Answers1

1

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?

ASDFGerte
  • 4,695
  • 6
  • 16
  • 33