factorial of a number

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

    I've seen a recursive approach used in many places (Eloquent JavaScript etc). Here, the function is called recursively until it reaches 0, which should not be the case. We should only call the function till it is >= 2 because the last number we need to multiply by is 1.

    It's a very minor change, and probably does not matter. Curious to know what other people think of it. Assuming it is a valid positive integer.

    /**
     * Popular approach - the recursive function is called till x is 0
     * 
     * @param x
     */
    function popularFactorial(x) {
        console.log(x)
        if(x === 0) {
            return 1
        } else {
            return x * popularFactorial(x - 1)
        }
    }
    var result = popularFactorial(8)
    console.log(result)
    
    /**
     * Using this approach, the recursive function is called one less time
     * i.e till x is 1
     * 
     * @param x 
     */
    function factorial(x) {
        console.log(x)
        if(x === 0) {
          return 1
        } else if(x >= 2) {
            return x * factorial(x - 1)
        }
        return x
    }
    var result = factorial(8)
    console.log(result)

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

    //This is fastest way to implement factorial
    const fact = n => !n ? 1 : n * fact(--n);
    
    console.log(fact(10))

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

    The important part of the function is this line:

     x = x * fact(x-1);
    

    but the fact function does not return a value, so this is the same as x * undefined. Try adding return x; to the bottom of your function.

    0 讨论(0)
  • 2020-12-09 12:43
    var factorialNumber , factorial=1;
    factorialNumber=prompt("Factorial Number" , "write Factorial Number");
    for(var i = 1; i<= factorialNumber;i++){
        factorial *= i;
    }
    alert(factorial);
    

    The code above first defines two variables, factorialNumber and factorial. factorial is initialized with 1. factorialNumber will get the result of the prompt (a number is expected) and then, using a cycle, in each step, factorial is multiplied with the index of the step, which is represented by i. When successfully calculated, we show the result using alert.

    0 讨论(0)
  • 2020-12-09 12:43
    function factorial(num){
        if(num<1||typeof num!=='number'){
        return undefined
      }
      if(num===1){
        return num
      }
        return num*factorial(num-1)
    }
    console.log(factorial(3))
    

    https://jsfiddle.net/mohittadhiyal/6w64x0sL/10/

    0 讨论(0)
  • 2020-12-09 12:43
    function factorial(n) {
        return [...Array(n + 1).keys()].slice(1).reduce((total, currentValue) => total * currentValue, 1);
    }
    
    0 讨论(0)
提交回复
热议问题