|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
P1009 [NOIP 1998 普及组] 阶乘之和 - 洛谷
- // #include<bits/stdc++.h>
- #include <iostream>
- #include <vector>
- using namespace std;
- // 计算两个大数相加
- vector<int> add(const vector<int>& a, const vector<int>& b) {
- vector<int> result;
- int carry = 0; // 进位
- int i = a.size() - 1; // 大数位数
- int j = b.size() - 1;
-
- while (i >= 0 || j >= 0 || carry > 0) {
- int sum = carry;
- if (i >= 0) sum += a[i--];
- if (j >= 0) sum += b[j--];
- result.insert(result.begin(), sum % 10);
- carry = sum / 10;
- }
- return result;
- }
- // 计算大数乘以一个整数
- vector<int> multiply(const vector<int>& num, int x) {
- if (x == 0) return {0};
- vector<int> result = num;
- int carry = 0; // 进位
-
- // 从最低位开始乘
- for (int i = result.size() - 1; i >= 0; i--) {
- int product = result[i] * x + carry;
- result[i] = product % 10;
- carry = product / 10;
- }
-
- // 处理剩余进位
- while (carry > 0) {
- result.insert(result.begin(), carry % 10);
- carry /= 10;
- }
- return result;
- }
- int main() {
- int n;
- cin >> n;
-
- vector<int> s = {0}; // 总和,从0开始
- vector<int> fact = {1}; // 当前阶乘值
-
- for (int i = 1; i <= n; i++) {
- fact = multiply(fact, i); // fact 每乘一次就是一个阶乘,即 i!
- s = add(s, fact); // 累加到总和 s = 1! + 2! + ... + n!
- }
-
- for (auto digit : s) {
- cout << digit;
- }
- return 0;
- }
复制代码 cpp难啊 |
|