Three ways to achieve js factorial algorithm

Three ways to achieve js factorial algorithm

// 非递归写法
function f(n) {
    if (0 === n) {
        return 1;
    }
    let res = 1;
    for (let i = 1; i <= n; ++i) {
        res *= i;
    }
    return res;
}

// 递归写法
function g(n) {
    if (0 === n) {
        return 1;
    }
    return n*g(n-1);
}

// 动态规划写法
let dp = [];
function h(n) {
    if (n < 0 || n !== Math.floor(n)) {
        return undefined;
    }
    if (dp[n]) {
        return dp[n];
    }
    if (0 === n) {
        dp[n] = 1;
        return 1;
    }
    for (let i = dp.length; i <= n; ++i) {
        dp[i] = dp[i-1]*i;
    }
    return dp[n];
}
Published 24 original articles · won praise 0 · Views 400

Guess you like

Origin blog.csdn.net/qq_18138105/article/details/105376295