Skip to content

Instantly share code, notes, and snippets.

@vpodk
Last active May 31, 2019 20:44
Show Gist options
  • Save vpodk/06f7ec88ca8830ea57bf47b6e5d375fa to your computer and use it in GitHub Desktop.
Save vpodk/06f7ec88ca8830ea57bf47b6e5d375fa to your computer and use it in GitHub Desktop.
Computing the factorial in JavaScript.
/**
* Computes the factorial of a given non-negative integer using iterative solution.
* @param {number} n The positive integer.
* @return {number} Returns a factorial of 'n'.
* @see https://en.wikipedia.org/wiki/Factorial
*/
function factorial(n) {
var result = 1;
for (var i = 1; i <= n; ++i) {
result *= i;
}
return result;
}
/**
* Computes the factorial of a given non-negative integer using `while` loop in reverse.
* @param {number} n The positive integer.
* @return {number} Returns a factorial of 'n'.
* @see https://en.wikipedia.org/wiki/Factorial
*/
function factorial(n) {
var result = 1;
while (0 < n) {
result *= n--;
}
return result;
}
/**
* Computes the factorial of a given non-negative integer using recursive solution.
* @param {number} n The positive integer.
* @return {number} Returns a factorial of 'n'.
* @see https://en.wikipedia.org/wiki/Factorial
*/
function factorial(n) {
return 2 > n ? 1 : n * factorial(n - 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment