在 C++ 中找出數字階乘中數字的總和


假設我們有一個數字 n,我們的任務是找出數字階乘中的數字總和。考慮 n = 5,那麼 n! = 120。所以結果為 3。

為了解決這個問題,我們將建立一個向量來儲存階乘數字,並用 1 初始化向量。然後,將 1 至 n 逐個乘到向量中。現在對向量中的所有元素求和並返回該數字總和

示例

 即時演示

#include<iostream>
#include<vector>
using namespace std;
void vectorMultiply(vector<int> &v, int x) {
   int carry = 0, res;
   int size = v.size();
   for (int i = 0 ; i < size ; i++) {
      int res = carry + v[i] * x;
      v[i] = res % 10;
      carry = res / 10;
   }
   while (carry != 0) {
      v.push_back(carry % 10);
      carry /= 10;
   }
}
int digitSumOfFact(int n) {
   vector<int> v;
   v.push_back(1);
   for (int i=1; i<=n; i++)
      vectorMultiply(v, i);
   int sum = 0;
   int size = v.size();
   for (int i = 0 ; i < size ; i++)
      sum += v[i];
   return sum;
}
int main() {
   int n = 40;
   cout << "Number of digits in " << n << "! is: " << digitSumOfFact(n);
}

輸出

Number of digits in 40! is: 189

更新於: 2019 年 12 月 19 日

427 次瀏覽

開啟您的職業生涯

完成課程以獲取認證

開始
廣告
© . All rights reserved.