factorial of a number

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

    Here is one I made using a while loop:

    function factorialize(num) 
    {
      i = 1;
      b = 1;
      while (i < num) {
        b = b + (b * i);
        i = i + 1;
        }
    return b;
    }
    
    0 讨论(0)
  • 2020-12-09 12:32

    I am not sure why no one used dynamic programming to answer this, it's by far the most efficient way to build something on a factorial in my view.

     var mem = [];
    
     function fact(num)
     {
        var x = parseInt(num);
    
        if (x == 0 || x == 1) return 1;
    
        mem[x] = x * fact(x-1);
    
        return mem[x];
     }
    
    0 讨论(0)
  • 2020-12-09 12:33

    My suggestion:

    function fact(x) {
        if (x<0) {
            return Infinity
        };
        var _= 1
        for ($=1;$<=x;++$) {
            _*=$
        };
        return _
    };
    

    It simply returns the factorial of whatever "x" is.

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

    A slight edit to Anton's code:

    function fact(x) {
       if(x>0)
           return x* fact(x-1);
       if(x===0)
           return 1;
       return null;
    
    }
    

    (factorial of a negative doesn't exist, but factorial of 0 is equal to 1, in this case, if a number is smaller than 0, the function will return null)

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

    a very simple form:

    function fact() {
        var x = document.getElementById("txtf").value;
        var f=1;
        for (var i=1; i <= x ; i++){
            f = f*i;
        }
        document.getElementById('showR').innerHTML= f;
    }
    
    
     <input type="text" id="txtf" value="3">
       <input type="button" id="btnf" value="click for calculate" onclick="fact()">
       <p id="showR">/Factoriel/</p>
    
    0 讨论(0)
  • 2020-12-09 12:36
    1. Your function doesn't return anything, ever.
    2. What do you do when x is 0?
    3. Minor point - apart from alert, you don't really do anything with the returned value.

    Try this instead, if you will (hover over the text):

    if(x==0) return 1;
    return x * fact(x-1);

    Working example: http://jsbin.com/apuka3/2

    0 讨论(0)
提交回复
热议问题