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?

3
  • 2
    Are you guaranteed to eventually hit a divisible number by continually doubling? Commented Sep 12, 2016 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. Commented Sep 12, 2016 at 15:16
  • Your algorithm is flawed. Are you maybe looking for this: stackoverflow.com/questions/147515/… ? Commented Sep 12, 2016 at 15:19

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.