Last active
February 4, 2017 11:52
-
-
Save railsstudent/d9de54fdffe4482dec7e3da760a2e100 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Sorry, I cheated. | |
// Idea comes from http://www.geeksforgeeks.org/factorial-large-number/ | |
function factorial(n){ | |
// Add some code | |
if (n < 0) { return null; } | |
var factArray = [1]; | |
var factSize = 1; | |
var carry; | |
var prod; | |
var digit; | |
for (var x = 2; x <= n; x++) { | |
// multiply each digit | |
carry = 0; | |
for (var i = 0; i < factArray.length; i++) { | |
prod = factArray[i] * x + carry; | |
digit = prod % 10; | |
carry = Math.floor(prod / 10); | |
factArray[i] = digit; | |
if (i === factArray.length - 1) { | |
while (carry > 0) { | |
digit = carry % 10; | |
carry = Math.floor(carry / 10); | |
factArray.push(digit); | |
} | |
break; | |
} | |
} | |
} | |
var strFactorial = ''; | |
for (var i = factArray.length - 1; i >= 0; i--) { | |
strFactorial += ('' + factArray[i]); | |
} | |
return strFactorial; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment