The Infinity approach to finding numbers

I’ve used this approach for all similar challenges in the past and I find it very straightforward. However, when I ran it this time for this particular challenge, at first it said there was a potential infinite loop detected, but after a couple seconds all conditions were checked and the test was passed. Is this an acceptable approach in a professional environment? In this problem we need to find the smallest number that is evenly divisible by every number between 1 and n. This was my solution:

function smallestMult(n) {
let nums = []
for (let i = 1; i <= n; i++) {
  nums.push(i)
}
  for (let j = n; j < Infinity; j++) {
    if (nums.every(a => j % a === 0)) {
      return j
    }
  }
}

smallestMult(20);

I am interested in this, too. I did something like:

for (let i = 1; ; i++)

I believe it’s similar thing, terminal condition will never be reached.

btw, I used such thing when solving this particular challenge

Yes, i’ll work. Slowly, but it’ll work. You could also use Number.MAX_VALUE, which seems a bit more realistic than Infinity.

However, what you have to bear in mind is that the point of it is to get you to figure out ways of making it run quickly (and by extension, making programs that crunch an ever-increasing numbers of ever-increasing numbers run quickly). You don’t have to do that, you can just do what you’ve done and move on. But that’s not quite in the spirit of the challenge, I would say.

Edit: basically all the algorithm questions are really common problems (be it school, college, university, job interviews, katas). And what they have in common is what I said there :point_up:. They are there to challenge you to do something other than just tick off that test – there are a million and one different ways to complete each one, you need to try different approaches, decide which one might be best in a given situation and why (what you’ve done is fine in certain situations, for example!)

1 Like

Don’t do this. If you are omitting a piece of the for loop, that’s a sign that you should not be using a for loop.

In general, if you don’t know how many iterations the loop should take, then you need a while loop.

I have some example in the link below.
There is my question about this, it’s slightly different than one from the topicstarter.
It is in the last post, there are couple more questions

Never heard of Number.MAX_VALUE, thanks!

1 Like