Last active
May 31, 2019 20:44
-
-
Save vpodk/06f7ec88ca8830ea57bf47b6e5d375fa to your computer and use it in GitHub Desktop.
Computing the factorial in JavaScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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