Large Factorials
题目
In mathematics, the factorial of integer n is written as n!. It is equal to the product of n and every integer preceding it. For example: 5! = 1 x 2 x 3 x 4 x 5 = 120
Your mission is simple: write a function that takes an integer n and returns the value of n!.
You are guaranteed an integer argument. For any values outside the non-negative range, return null, nil or None (return an empty string "" in C and C++). For non-negative numbers a full length number is expected for example, return 25! = "15511210043330985984000000" as a string.
For more on factorials, see http://en.wikipedia.org/wiki/Factorial
NOTES:
- The use of BigInteger or BigNumber functions has been disabled, this requires a complex solution
- I have removed the use of require in the javascript language.
分析
阶乘,问题在于js对数字长度有限制,超长之后就会直接返回infinity。
解决方案就是把数字拆成数组,对每一位单独进行运算,按照逢十进一的规则加到数组的下一项里。最后把数组翻转并组合就是所需要的答案
另外,python3里面没有长度限制,直接计算就可以了。额外附上python3的代码。
答案
- JavaScript
function factorial(n) {
// 按照位数算,把数字用数组表示
if (n < 0) return null
if (n < 2) return "1"
let result = [1];
for (let i = 2; i < n + 1; i++) {
for (let j = 0, plus = 0; j < result.length || plus != 0; j++) {
let count = (j < result.length) ? (i * result[j] + plus) : plus
result[j] = count % 10
plus = (count - result[j]) / 10
}
}
return result.reverse().join("")
}
- python3
def factorial(n):
sum=1
if n<0:
return null
elif n==0 or n==1:
return "1"
else:
for i in range(1,n+1):
sum*=i
print len(sum)
return sum

