Factorialize a Number (242) - Correct result - not able to submit

Factorialize a Number (242) - Correct result - not able to submit
0

#1

Hi,

I have a quick question,
anyone knows why following code doesn’t allow me submit.
Results are correct:

arrayVal = [];
var j = 1;

function factorialize(num) {
if(num === 0){
return 1;
}else{

for(var i = 1; i < num + 1; i++ ){
arrayVal = j *= i;

}
}
return arrayVal;
}
factorialize(20);

Regards
Konrad


#2

I haven’t started playing with it yet, to see where you went wrong, but copy/pasting it as you posted here I didn’t get the correct result at all.

Okay, now I played with it and it was quite simple: put your

arrayVal = [];
var j = 1;

inside the function.


#3

so were you allowed to submit that solution?


#4

ok I can see that now. Thx


#5

after I moved those variable declarations, yes. (as a side note, don’t forget to declare your variable with the var keyword, so that you don’t have any scope leakage) like this:

function factorialize(num) {
  var arrayVal = [];
  var j = 1;

  if(num === 0){ 
    return 1; 
  }else{
    for(var i = 1; i < num + 1; i++ ){
      arrayVal = j *= i;
    }
  }
  return arrayVal;
}
factorialize(20);

#6

A couple notes. yes, that solution works, but in addition to using the var on the arrayVal variable, that variable does not need to be an array, and the j variable is unnecessary. just set arrayVal = 1 or, I suppose just `val = 1`` :wink:

and then ditch the j from your loop making it just val *= i

thus:

function factorialize(num) {
  var val = 1;

  if(num === 0) return 1; 
  else for(var i = 1; i < num + 1; i++ ) val *= i;
  
  return val;
}

#7

Thanks for this it’s definitely much cleaner now.


#8

function factorialize(num) {

if(num===0) return 1;
var j = 1;
for(var i = 0; i < num; i++){
var c = (j+=(i*j));
}return c;

}

factorialize(10);