在 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP