简体   繁体   English

JavaScript中是否有用于找到数字阶乘的内置方法?

[英]Are there any build-in methods in JavaScript for finding the factorial of a number?

Are there any build-in methods for finding the factorial of a number which we can use in place of reusable functions like the example below: 是否有用于找到数字阶乘的内置方法,我们可以使用这些方法代替可重用的函数,例如下面的示例:

 function factorial(x) { for (let i = x - 1; i >= 1; i--) { x= x * i; } return x; } alert(factorial(16)); 

不可以, Math对象确实不提供这种方法。

There is no in-build factorial function. 没有内置的阶乘功能。 However, as a side note, you can simplify your function as following 不过,请注意,您可以按以下方式简化功能

 function factorial(x) { return (x > 1) ? x * factorial(x-1) : 1; } console.log(factorial(5)); 

There are no built-in functions to do the factorial of a number in JavaScript, but you could make a .js file just for this purpose, and import it in each file you intend to use it for. 没有内置函数可以执行JavaScript中数字的阶乘,但是您可以为此创建一个.js文件,并将其导入要使用的每个文件中。
Take a look at this question: How do I include a JavaScript file in another JavaScript file? 看一下这个问题: 如何在另一个JavaScript文件中包含一个JavaScript文件? for importing files. 用于导入文件。 I believe this is the closest you can get for what you want. 我相信这是您所需要的最接近的产品。

As Nikos already mentioned in a comment, you should beware overflowing for large factorial numbers, as the highest number you can get to is 2^53 - 1 for integers, or 2^32-1 for bitwise operations. 正如Nikos在评论中已经提到的那样,您应该当心较大的阶乘数,因为整数可以得到的最大数是2 ^ 53-1,对于按位运算则是2 ^ 32-1。 Make your own BigInt library, or search for one: there exist many open-source ones out there. 制作自己的BigInt库或搜索一个库:那里有很多开源库。

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

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