DEV Community

Heriberto Garcia Ribas
Heriberto Garcia Ribas

Posted on

What is faster then a FOR..Loop in JS?

Hello everyone, I hope you are doing good!

I am not sure if this is the right way to ask a question in here? Forgive me in that case. I just joined the community. But I hope somebody can help me by pointing me in the right direction?

I am sitting at the moment in a coffee bar in The Hague (The Netherlands), not be confused with a coffee shop! ;) I am getting frustrated about a seemingly easy Javascript Kata...grrrr! So maybe a coffee shop would be a good idea at this point :)

The Kata instruction:
Given a number n, return the number of positive odd numbers below n.
Expect Large Inputs!

My first solution was to loop using a simple For..Loop from 0 to n-1:

for (let i=0;i<n;i++){if (i % 2 != 0) count++}

Codewars returned the error
Execution Timed Out (12000 ms)

So I thought to make the loop a bit smarter and not loop through all the numbers but only looping through the odd numbers like this:

for (let i=1;i<n;i+=2){if (i % 2 != 0) count++}

But this is still not fast enough for Codewars.
Googling didn't help me find an answer. So I am hoping somebody here knows what I am overlooking? Or is this a Codewars glitch? I tried several times on different days.

Thanks in advance!
Happy coding!

Heriberto

Top comments (2)

Collapse
 
montanacoder profile image
Jeremy • Edited

This one was tricky for me too. you may be overthinking this. To answer you header question, while loops and recursion are loops that will be faster than a for loop if I am not mistaken. As for the problem, without giving you the answer, (I am bad with hints) try reading the question like this, " how many numbers does "n" have odd and even" (maybe that will help, i know it triggered my brain)? meaning, if we split the number in half we will get 12 even and 1/2 odd (not fully but close) so if we take the number 3 for easy math (haha) 3 = 1 even (2) and 1 odd (1),
do the same thing with 7, 7= 3 even (6,4,2) and 3odd(5,3,1) and 15 = 7even (14,12,10,8,6,4,2) and 7odd (13,11,9,7,5,3,1) but if we take the number "n" and divide it in half we will end up .5 at the end ie (n=15 => 7.5) from there you will want to look at Math Method to achieve the correct answer. I hope I helped and didn't confuse you. your final answer should be one line

developer.mozilla.org/en-US/docs/W...

Collapse
 
hgarr profile image
Heriberto Garcia Ribas
hgarr image

OMG of course! I was overthinking it indeed.
There is no need for a loop.

Math.floor(n/2)

From now on I will take on the Kata's with a different perspective!
Thanks Jeremy! :)