大數的階乘


在計算機中,變數儲存在記憶體位置。但記憶體位置的大小是固定的,所以當我們要找到一些更大值(例如 15!或 20!)的階乘時,階乘值將超出記憶體範圍並返回錯誤結果。

對於大數的計算,我們必須使用陣列來儲存結果。在陣列的每個元素中,都儲存結果的不同位數。但這裡我們無法直接將某些數字與陣列相乘,我們必須對結果陣列的所有位數執行手動乘法過程。

輸入和輸出

Input:
A big number: 50
Output:
Factorial of given number is:
30414093201713378043612608166064768844377641568960512000000000000

演算法

multiply(x, multiplicand)

輸入:數字 x,和作為陣列的大乘數。

輸出:相乘後的結果。

Begin
   carry := 0
   for all digits i of multiplicand, do
      prod := i*x+carry
      i := prod mod 10
      carry := prod / 10
   done

   while carry ≠ 0, do
      insert (carry mod 10) at the end of multiplicand array
      carry := carry/10
   done
End

factorial(n)

輸入:數字 n。

輸出:求 n 的階乘。

Begin
   define result array.
   insert 1 in the result

   for i := 2 to n, do
      multiply(i, result)
   done

   reverse the result
   return result
End

範例

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

void multiply(int x, vector<int>&multiplicand) {    //multiply multiplicand with x
   int carry = 0;     // Initialize carry to 0
   vector<int>::iterator i;

   for (i=multiplicand.begin(); i!=multiplicand.end(); i++) {   //multiply x with all digit of multiplicand
      int prod = (*i) * x + carry;
      *i = prod % 10;       //put only the last digit of product
      carry  = prod/10;    //add remaining part with carry  
   }

   while (carry) {    //when carry is present
      multiplicand.push_back(carry%10);
      carry = carry/10;
   }
}

void factorial(int n) {
   vector<int> result;
   result.push_back(1);    //at first store 1 as result

   for (int i=2; i<=n; i++)
      multiply(i, result);   //multiply numbers 1*2*3*......*n

   cout << "Factorial of given number is: "<<endl;

   reverse(result.begin(), result.end());

   vector<int>::iterator it;    //reverse the order of result

   for(it = result.begin(); it != result.end(); it++)
      cout << *it;
}

int main() {
   factorial(50);
}

輸出

Factorial of given number is:
30414093201713378043612608166064768844377641568960512000000000000

更新於: 17-6 月 -2020

2K+ 瀏覽

開始你的職業

完成課程以獲取證書

開始
廣告