factorial of a number

前端 未结 28 2440
滥情空心
滥情空心 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:49

    function fact(n) {
      if (n > 1) {
        return n * fact(n-1);
      } else {
        return 1;
      }
    }
    console.log(fact(5));
    

    Using ternary operator we replace the above code in a single line of code as below

    function fact(n) {
          return (n != 1) ? n * fact(n - 1) : 1;
     }
    console.log(fact(5));
    

提交回复
热议问题