Problem Description:
In mathematics, the factorial of an integer is n
written as n!
. It is equal to the product of and n
every integer preceding it. For example:5! = 1 x 2 x 3 x 4 x 5 = 120
Your mission is simple:write a function, takes an integer and n
returns the value of n!
.
You is guaranteed an integer argument. For any values outside the Non-negative range, return null
, nil
or None
(return a empty string ""
in C D C + +). For non-negative numbers a full length number was expected for example, return as 25! = "15511210043330985984000000"
a string.
For more on factorials, see http://en.wikipedia.org/wiki/Factorial
Problem Solving Ideas:
In the beginning it is normal to use a for loop or a recursive factorial. And then found that JS number has a bit limit (n number is relatively large, will be in scientific notation to render the results; When n is large, it crosses the border, Infinity). In short, it is not as if the title requires the display of all the numbers.
Reference Blog: https://www.cnblogs.com/h5course/p/7566812.html
By multiplying the large number, you can use an array to store each digit, and the basic solution method can be analogous to the math multiplication in primary school. (When 24*5, first with the 4*5 20, the single digit is 0, the carry is 2, and then 2*5+2 12, then 10 bits 2, carry 1,. The last is [0,2,1]. When the array is inverted, it is the multiplication result. )
My answer:
functionfactorial (n) {//Add Some code if(n<0) {return NULL;} if(N==0 | | N==1) {return"1";} Let result=[1]; //result Array Stores current factorial results for(Let num=2;num<=n;num++){ for(Let i=0,plus=0; I<result.length | | plus!=0; i++) {Let Count= (i<result.length)? (num*result[i]+Plus):p LUs; //If the current I is less than the number of digits stored in the result, the *num+plus are respectively; Result[i]=count%10; //Bits, 10, hundred ... On the number, stored in the array result plus= (Count-result[i])/10; } } returnResult.reverse (). Join (""); //After the array is reversed, that is the final factorial result }
Excellent answer:
function factorial (n) { var res = [1]; for (var i = 2; I <= n; ++i) { var c = 0; //c for rounding for (var j = 0; J < res.length | | c!== 0 ++j) {C /span>+= (Res[j] | | 0) * I; RES[J] = c% 10; //to find out bits, 10, hundred ... The number of c = Math.floor (C/10 return res.reverse (). Join ("
Also found directly in Python do, there is no such problem arises. (Recursive method)
def Fun (n): if n<0: return null elifor n==1: return"1" Else: return N*fun (n-1)
Use for loop
def Fun (n): sum=1 if n<0: return null elifor n==1: return"1" Else: for in range (1,n+1): sum*=i return sum
Haha, huh!
Codewars--js--large factorials--factorial + large number factorial