factorial of a number

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

    I wrote this and it works.

      var d = 1;
      for (num; num > 1; num--) {
        d *= num;
      }
      return d;

    0 讨论(0)
  • 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));

    0 讨论(0)
  • 2020-12-09 12:37
        function factorial(num) {
    
        var result = 1;
    
        for (var i = 1; i <= num; i++) {
            result = result * i;
    
        }
    
        return result;
    }
    //call function e.g factorial(4).. 1*2*3*4 it will evaluate in ascending order
    
    0 讨论(0)
  • 2020-12-09 12:38

    Use loop its easy to implement

    function fact(num)
    {
        if(num<0)
         return "Undefined";
        var fact=1;
        for(var i=num;i>1;i--)
          fact*=i;
        return fact;
     }
    
    <input type="button" value="Find factiorial" onclick="alert(fact(6))">
    
    0 讨论(0)
  • 2020-12-09 12:38
    function factorial(n) {
      return (n != 1) ? n * factorial(n - 1) : 1;
    }
    
    alert( factorial(5) );
    

    You can try to use recursion method

    0 讨论(0)
  • 2020-12-09 12:39

    1) When X=0 function should return 1; 2) Added return;

     function fact(num)
     {
        var x=parseInt(num);
        //alert(x+1);
        if(x>0)
            x=x* fact(x-1);
        else
            x=1;
        return x;
     }
    

    usage

    <input type="button" value="Find factiorial" onclick="alert(run(fact.value));">
    
    0 讨论(0)
提交回复
热议问题