57 lines
1.6 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## 1、求N的值 【问题描述】
用高精度方法求N的精确值(N以一般整数输入)。
【输入样例】ni.in
```in
10
```
【输出样例】ni.out
```out
3628800
```
```cpp
#include<iostream> // 引入输入输出流库,用于 cin 和 cout
#include<string> // 引入字符串库,支持 string 类型
#include<vector> // 引入向量容器,用于存储中间结果
using namespace std;
// 高精度字符串乘法函数:将一个大整数(字符串形式)与一个整数相乘
string multiply(string res, int num) {
vector<int> temp; // 存储乘法结果的每一位(倒序)
int carry = 0; // 进位值初始化为0
// 从低位到高位逐位相乘
for (int i = res.size() - 1; i >= 0; i--) {
int product = (res[i] - '0') * num + carry; // 当前位乘积 + 进位
temp.push_back(product % 10); // 当前位结果
carry = product / 10; // 更新进位
}
// 处理最后的进位
while (carry) {
temp.push_back(carry % 10);
carry /= 10;
}
// 将结果翻转并转换为字符串
string result;
for (int i = temp.size() - 1; i >= 0; i--) {
result += temp[i] + '0'; // int 转为字符
}
return result;
}
int main() {
int n;
cin >> n; // 输入要计算的阶乘数字 n
string result = "1"; // 初始结果为 1阶乘起始值
// 从 2 乘到 n不断更新结果
for (int i = 2; i <= n; i++) {
result = multiply(result, i); // 累乘
}
cout << result << endl; // 输出 n 的阶乘
return 0;
}
```