Algorithm: Factorialize a Number Douts!

Algorithm: Factorialize a Number Douts!
0

#1

I’m doing the factorialize algorithm challenge and I would really appreciate if someone with a greater knowledge than me would explain me what’s wrong in the thinking process of my code

Im following these steps to factorialize a number:

  1. Create a function with a parameter (num).

  2. I create an if statement to accomplish the next task: factorialize(0) should return 1. If (num === 0) {return 1;}

  3. Create an array inside the function.

  4. Create a loop to iterate through num-1 numbers and push them into the array. So we add the current number + all the previous values to the array. Example: If our number is 5 we add 5, 4, 3, 2, 1.

  5. Use the reduce method into the array to multiply the values of each number in the array (factorialize).

  6. Return the given value.

function factorialize(num) {
  
  if (num === 0) { return 1; }
  
  else {var array = [];
        
    for(i = num; i >= 1; i--){
      var newArray = array.push[i];
      newArray.reduce(function(previousVal, currentVal){
      return previousVal * currentVal;
      });
    }
  }
}

factorialize(5);

I am mainly getting 2 douts now. This way to solve the algorithm might not be the most efficient one okay but:

  1. Is this a viable way to solve it?

  2. Why am I getting “cannot read property ‘reduce’ of undefined”.

Link to the challenge:


#2

You don’t need to use an array here: you can just use a loop and multiply numbers. But if you use reduce, you use it on an existing array. So you need to build the array first and then apply reduce to the array you’ve built, not call it in the loop you have.


#3

Thank you very much!


#4

function factorialize(num) {

return (num != 1 && num !=0) ? num * factorialize(num - 1) : 1;

return num;
}

factorialize(5);