factorial of a number

前端 未结 28 2430
滥情空心
滥情空心 2020-12-09 11:57

I have the following code but it is not giving perfect result for factorial can u find it out plz



        
28条回答
  •  伪装坚强ぢ
    2020-12-09 12:36

    Recursion in JS is open to stack overflow error and also very slow. Looping by other means is better. My contribution to factorial code would be a straightforward one;

    var fact = n => n > 0 ? Array.from({length: n}, (_,i) => i+1)
                                 .reduce((p,c) => p*c)
                          : 1;
    console.log(fact(5));

提交回复
热议问题