P1009
高精度+阶乘
很久以前刚开始搞算法写的一道题,不难,可作为新手题。
那时码风还有点奇怪~
思路: 用arr
数组,从1开始,存储每次乘一个数(高精度乘低精度)的结果 (即为当前数的阶乘),然后每乘完一次就进行一次加法(高精度加高精度),结果存储在ans
数组中,最后逆序输出即可。注意代码中细节!
话不多说,干代码:
#include <cctype>
#include <string>
#include <stack>
#include <set>
#include <vector>
#include <queue>
#include <iostream>
#include <algorithm>
#define LL long long
#define INF 1000000001
using namespace std;
const int maxn = 1002;
int arr[maxn], ans[maxn];
bool flag;
void s_plus(int arr[], int ans[]) { //高精度之和
int jinwei = 0;
for (int i = 1; i <= 1000; i++) {
ans[i] += arr[i] + jinwei;
jinwei = ans[i] / 10;
ans[i] %= 10;
}
}
void mul(int arr[], int x) { //高精度乘低精度
int jinwei = 0;
for (int i = 1; i <= 1000; i++) {
arr[i] = arr[i] * x + jinwei;
jinwei = arr[i] / 10;
arr[i] %= 10;
}
}
int main() {
int n;
cin >> n;
arr[1] = 1; //第一位为1
for (int i = 1; i <= n; i++) {
mul(arr, i);
s_plus(arr, ans); //算完一次阶乘就加一次
}
for (int i = 1000; i >= 1; i--) { //注意!一定是逆序输出,也可方便处理结果中有0的情况
if (ans[i] != 0) flag = 1;
if (flag) cout << ans[i];
}
return 0;
}