简体   繁体   English

Javascript代码改进-整数阶乘

[英]Javascript Code improvement - Integer factorial

I am learning to code with Javascript and one exercise is about returning the factorial of a provided integer. 我正在学习使用Javascript进行编码,一种练习是关于返回提供的整数的阶乘。 For example: 5! 例如:5! = 1 * 2 * 3 * 4 * 5 = 120 = 1 * 2 * 3 * 4 * 5 = 120

I came up with a result and it was accepted. 我想出了一个结果,它被接受了。 However, I am not so sure it would be the most efficient way of solving this. 但是,我不确定这将是解决此问题的最有效方法。

Anyone would have any tips on how to improve this code? 任何人都将对如何改进此代码有任何提示?

function factorialize(num) {
    var array = [];  
    for (i = 1; i <= num; i++) {
        array.push(i);
    }
    var multi = 1;
    for (var i = 1; i < array.length; i++) {
        multi *= array[i];
    }
    return multi;
} 

Many thanks!! 非常感谢!!

You have several approaches to get a solution. 您有几种解决方案。

  1. by iteration 通过迭代

     function f(n) { var r = n; while (--n) { r *= n; } return r; } 
  2. by recursion 通过递归

     function f(n) { return n === 0 ? 1 : n * f(n - 1); } 

    or a very short version 或非常简短的版本

     function f(n) { return +!~-n || n * f(n - 1); } 

Why don't you use 你为什么不使用

var ans=1;
for (i=1;i<=num;i++)//for(i=num;i>=1;i--)
{
    ans=ans*i;
}
return ans;

I have used this kind of recursive method 我已经使用了这种递归方法

function f(p) {
    if (p==1) return;
    p -= 1;
    x = x * p;
    f(p);        
}

A corrected version (with comments) : 更正的版本(带有注释)

function f(p) {
    if (p == 0) return 1;    /* 0! == 1 by definition,    */
    return p * f(p - 1);     /* otherwise p! = p * (p-1)! */
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM