Reputation: 16311
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));
Upvotes: 1
Views: 2759
Reputation: 732
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.
Take a look at this question: How do I include a JavaScript file in another JavaScript file? 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. Make your own BigInt library, or search for one: there exist many open-source ones out there.
Upvotes: 0
Reputation: 28475
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));
Upvotes: 0