Getting Half Of The Results In An Array

This has stumped me for a bit, and I can’t make logical sense of it. I always get half of the array (computeFactorialOfN(4) --> end value is 2 , computeFactorialOfN(100) --> end value is 50). This is part of a larger exercise to get a factorial, and I’m thinking of having the code below to put all the numbers below n in an array and in a later function multiply all those values together and returning the answer. Here’s the code:

function computeFactorialOfN(n) {
  var factorial = [] // this is the array 

  for (var i = 0; i <= n; i++) {  // i is 0; if i is <= 0,; increment i 
      factorial.push(n) //push that value to var factorial 
      n-- // and decrement (n = 6, so n would be 5 then 4 then 3 etc.
   return factorial //return the array
computeFactorialOfN(6) // --> [6, 5, 4, 3]

I’m expecting to get [6, 5, 4, 3, 2] (I’m not bothering with multiplying by 1), but I’m not. Thoughts about my strategy and the code snippet are welcome.

Wait, I see your logic. Here’s the problem.

In this line you increment i by 1 with every loop.

This line you decrement n by 1 with every loop.

So in reality, you’re cutting your loop in half, because i <= n gets closer to true by 2 each loop, not by 1.

1 Like