问题描述:
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
解题思路:
刚开始就是按照寻常情况,直接就用for循环或是递归求阶乘。然后发现js的Number有位数限制(n数相对较大时,会以科学计数法呈现结果;n数很大时,越界,Infinity)。总之就不能像是题目要求的显示所有的数字。
参考博客:https://www.cnblogs.com/h5course/p/7566812.html
得出大数相乘,可以用数组来存储每一位数字,基本求解方法可以类比于小学数学乘法计算。(当24*5时,先用4*5得20,则个位数为0,进位为2;再用2*5+2得12,则十位为2,进位为1,。最后为[0,2,1]。数组倒置后即为乘法结果。)
我的答案:
function factorial(n){ // Add some code if(n<0){return null;} if(n==0 ||n==1){return "1";} let result=[1]; //result数组存储当前阶乘结果 for(let num=2;num<=n;num++){ for(let i=0,plus=0 ; i){ let count=(i plus):plus; //若当前i小于result所存数字的位数,则分别*num+plus;若等于,则直接进位。 result[i]=count%10; //个位、十位、百位……上的数字,存放在数组result中 plus=(count-result[i])/10; } } return result.reverse().join(""); //将数组result倒序后,即为最后的阶乘结果 }
优秀答案:
function factorial(n) { var res = [1]; for (var i = 2; i <= n; ++i) { var c = 0; //c代表进位 for (var j = 0; j < res.length || c !== 0; ++j) { c += (res[j] || 0) * i; res[j] = c % 10; //分别求出个位、十位、百位……的数 c = Math.floor(c / 10); } } return res.reverse().join(""); }
另外发现直接用python做,就没有这个问题出现。(用递归方法)
def fun(n): if n<0: return null elif n==0 or n==1: return "1" else: return n*fun(n-1)
用for循环
def fun(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 return sum
哈哈哈!