1

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));
AndrewL64
  • 15,794
  • 8
  • 47
  • 79
  • 1
    there are no built-in methods and trying to compute a large factorial eg (50) will overflow most probably you will need a bigint library for any serious factoial computation – Nikos M. Dec 21 '18 at 11:42
  • 1
    Possible duplicate of [What is the fastest factorial function in JavaScript?](https://stackoverflow.com/questions/3959211/what-is-the-fastest-factorial-function-in-javascript) – Liam Dec 21 '18 at 11:49

3 Answers3

1

No, the Math object does provide no such method.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

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));
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
0

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.

mazunki
  • 682
  • 5
  • 17