1. 程式人生 > >codewars--js--Large Factorials--階乘+大數階乘

codewars--js--Large Factorials--階乘+大數階乘

ref 階乘 clas python count .cn exp pre n+1

問題描述:

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<result.length || plus!=0 ; i++){ let count=(i<result.length)?(num*result[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

哈哈哈!

codewars--js--Large Factorials--階乘+大數階乘