Kōdo no musō-ka - 8 months ago 36

Javascript Question

I'm learning javascript. I have written a none recursive function which I want to return the factorial of a given number.

`function factorialize(n) {`

for(var i = 0; i < n; i++) {

n *= i;

}

return n;

}

factorialize(5);

so result should be

`120`

I keep getting

`0`

Answer

You are looping from 0 to n ...Multiplyin any number with 0 will be 0 another thing ,you are looping it till n and incrementing with i in every loop ,it goes into infinite loop

change it to the following

```
function factorialize(n) {
var length=n;
if(n==0) return 1;
for(var i = 1; i < length; i++) {
n *= i;
}
return n;
}
console.log(factorialize(5));
```

Hope it helps

Source (Stackoverflow)