Factorialize a Number - unable to complete

Factorialize a Number - unable to complete
0

#1

Tell us what’s happening:

Your code so far

var numbers = [];
function factorialize(num) {
  result = 1;
  if (num == 0){
    return 1;
     } else {
       
       while (num > 0) {
         numbers.push(num);
         num -= 1;
       }
       var sum = 1;
       for (var i =0; i < numbers.length; i++) {
        sum *= numbers[i];
       }
       num = sum;
     }
  return num;
}

factorialize(5);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36.

Link to the challenge:


#2

I have figured the answer to the problem myself. The var numbers should have been initialized inside the function. Not that my previous code was wrong, but for some reason fCC would not accept is as a correct solution.


#3

It is good that you have got it working. You can also try using recursive function to get the result but with a smaller code, and you won’t need any for or while loop :slight_smile:


#4

Your first solution didn’t pass the test because is in fact “wrong”.

This is because by using a global variable you are not “initialising” it as an empty array at each function calls, but as a matter of fact remains dirt with the previous values.

The tests call function sequentially so the second iteration will produce a wrong result.

You can test this by simply calling:

factorialize(2); // returns 2
factorialize(3); // returns 12 || expected 6

That is because numbers still holds 2 as a value.

And that’s why global variable are generally displeased (and a pain to debug)


#5

Thank you for explaining the hazards of using global variables. Every time I tested the code on the FCC challenge screen it it must have reset the global variable so my solution looked correct. The code it a bit ugly but I am enjoying the challenges and coming to grips with JS.

Here is an improved version:

function factorialize(num) {
  var numbers = [];
  result = 1;
  if (num == 0){
    return result;
     } else {
       
       while (num > 0) {
         numbers.push(num);
         num -= 1;
       }
        for (var i =0; i < numbers.length; i++) {
        result *= numbers[i];
       }
      
     }
  return result;
}

#6

I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.