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
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.
so were you allowed to submit that solution?
ok I can see that now. Thx
1 Like
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);
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``
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;
}
Thanks for this it’s definitely much cleaner now.
1 Like
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);