Factorialize a number Test HELP ME!


#1

This is for algorithm challenge “Factorialize a Number”.

Someone please help me. I have read the thread about this topic and it is now closed. I have seen numerous people do it different ways, and this was my solution. It seems like it should work, but I can’t pass the test. I understand the logic here. Please help me! Here is my code:

function factorialize(num) {
var arr = [];
for (var i = 1; i <= num; i++) {
arr.push(i);
// gives you [1,2,3,4,5]
var answer = arr.reduce( function(a,b){
return a * b;
});
return answer;
}}

factorialize(5);
//WHY DOESN’T THIS WORK!!!


#2

You’re missing square bracket after arr.push(i)
And there are two square brackets after return answer. Should be one


#3

Check your brace after your for loop. Also, be sure to consider the base case (0!)


#4

IT WORKS! Thank you guys so much! Figured it was syntax! Thought I was losing my mind!!! REEEEEEEEEEEEEEEEEEEEEEEEEEEEE


#5

Here’s your code formatted:

function factorialize(num) {
  var arr = [];
  for (var i = 1; i <= num; i++) {
    arr.push(i);
    // gives you [1,2,3,4,5]
    var answer = arr.reduce(function(a, b) {
      return a * b;
    });
    return answer;
  }
}

factorialize(5);

A return will exit the loop immediately, so your loop only loops one time. To fix this, move your reduce() and return outside of the loop:

function factorialize(num) {
  var arr = [];
  for (var i = 1; i <= num; i++) {
    arr.push(i); // gives you [1,2,3,4,5]
  }
  var answer = arr.reduce(function(a, b) {
    return a * b;
  });
  return answer;
}

factorialize(5);

And don’t forget to check for times when num might be less than 1. :wink:

Edit: Ninja’d by the OP lol


#6

Yes that is a good answer! My code failed when the argument was zero, so im thinking of putting an if statement in there specifically for zero (or #'s < 1) that returns a “0”.


#7

Still doesn’t work. I need to work on my syntax.

function factorialize(num) {
var arr = [];
if (num <= 0) {
return 0;
}
for (var i = 1; i <= num; i++) {
arr.push(i)};
// gives you [1,2,3,4,5]
var answer = arr.reduce( function(a,b){
return a * b;
});

return answer;
}

factorialize(5);
//REEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE


#8

Here’s a hint, look at the expected return value for the failing test case and compare that with what you are returning:


#9

I am retarded lol. I asked it to return the wrong number haha. Thanks for pointing that out. This is my first language outside of html and CSS but I really enjoy how the logic works. Sometimes I get in too much of a hurry need to slow down. Appreciate the help man!!!