[solved] Factorialize a Number (get right outputs but can't pass)

Running it on Repl.it, I get the right answers for the FreeCodeCamp’s tests (

`factorialize(5)` should return 120.

`factorialize(10)` should return 3628800.

`factorialize(20)` should return 2432902008176640000.

`factorialize(0)` should return 1.

, but I can’t pass FreecodeCamp’s tests.

I know the below isn’t elegant (saw the recursive answer on hint by now, but code below works). This is my code:

let i = 1
function factorialize(num) {
let fact = num;
if (num == 1) {
  fact = 1;
} 
if (num == 0) {
  fact = 1;
} 
while (i < num) { 
  fact *= (num-i) ;
  i++
}
return fact;
}

Any pointers?

What FCC says when you run the test ?

Also, the first if is useless, you do “let fact = num” so if num = 1 fact = 1.

Thanks for reverting.

Agreed on the first if being useless. Just removed it.

let i = 1

function factorialize(num) {

let fact = num;

if (num == 0) {

fact = 1;

}

while (i < num) {

fact *= (num-i) ;

i++

}

return fact;

}

That doesn’t impact the result though. Still can’t pass with this code.

FCC gives :

// running tests

factorialize(5) should return 120.

factorialize(10) should return 3628800.

factorialize(20) should return 2432902008176640000.

// tests completed

I can only pass first and last tests in FCC despite that the code works.

What am I missing?

Ok, I found your error.

Your code should be inside the function, so the “let i = 1” put it inside.

One more thing, when num == 0 you can directly return 1 so that the function end and it will not execute the rest of the code.

Super, I’ll keep in mind trying out the variable declaration (for the sake of passing the test). And thanks for the note on placing a return earlier, appreciated.

Thanks for your help @JohnPA! :slight_smile: