Face questions of: js achieve factorial

Factorial equation is: n = 1 * 2 * 3 * 4 * ... * (n-2) * (n-1) * n!

 

Input a n, factorial achieved. code show as below:

// Public html portion
 < P > 
    Enter: 
    < INPUT type = "text" ID = "INPUT" placeholder = "Please enter an integer n-"  /> 
</ P > 
< Button the onclick = "SET ()" > Button </ Button > 
< div class = "result" > 
    results: < div ID = "result" > </ div > 
</ div >

 

Method One: recursive

function set(){ // 入口函数
    let n = document.getElementById('input').value
    let res = this.math(n)  // 结果
   
    document.getElementById('result').innerText = res
}

function math(n){ // 递归函数
    if(n < 0){
        return -1
    }else if(n === 0 || n === 1){
        return 1
    }else{
        return n * this.math(n-1)
    }
}

 

Method two: while ()

function set(){
    let n = document.getElementById('input').value
    let res = n  // n = n * (n-1) * (n-2) * ... * 2 * 1
   
    if(n < 0){
        res = -1
    }else if(n === 0 || n === 1){
        res = 1
    }else{
        while(n > 1){
            n--    // 递减
            res *= n
        }
    }

    document.getElementById('result').innerText = res
}

 

Method three: for loop

Ideas and while, like decreasing the use of multiplying ideas.

 

Guess you like

Origin www.cnblogs.com/bala/p/11767371.html