传送门
P1009 [NOIP1998 普及组] 阶乘之和 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
思路
这题看似简单,用long long一开
#include<bits/stdc++.h>
using namespace std;
long long n, s = 0;
int main() {
cin >> n;
for (int i = 1; i <= n; ++i) {
long long g = 1;
for (int j = 1; j <= i; ++j)
g *= j;
s += g;
}
cout << s;
return 0;
}
50pts
所以高精度走起
高精加
void j() {
for (int i = 1; i <= len; ++i) {
b[i] += a[i];
if (b[i] >= 10) { //进位
b[i + 1] += b[i] / 10;
b[i] %= 10;
}
now_len = max(now_len, i);
}
}
高精阶乘
void jc(int x) {
for (int i = 1; i <= h; ++i) {
a[i] *= x;
}
for (int i = 1; i <= h; ++i) {
if (a[i] >= 10) { //进位
a[i + 1] += a[i] / 10;
a[i] %= 10;
}
}
while (a[h + 1] > 0) {
h++;
a[h + 1] = a[h] / 10;
a[h] %= 10;
}
if (a[h + 1] > 0)
h++;
len = h;
}
整起来
代码
#include<bits/stdc++.h>
using namespace std;
int a[1000001], b[1000001], n, len = 1, h = 1, now_len = 0;
void jc(int x) { //高精阶乘
for (int i = 1; i <= h; ++i) {
a[i] *= x;
}
for (int i = 1; i <= h; ++i) {
if (a[i] >= 10) { //进位
a[i + 1] += a[i] / 10;
a[i] %= 10;
}
}
while (a[h + 1] > 0) {
h++;
a[h + 1] = a[h] / 10;
a[h] %= 10;
}
if (a[h + 1] > 0)
h++;
len = h;
}
void j() { //高精加
for (int i = 1; i <= len; ++i) {
b[i] += a[i];
if (b[i] >= 10) { //进位
b[i + 1] += b[i] / 10;
b[i] %= 10;
}
now_len = max(now_len, i);
}
}
int main() {
cin >> n;
memset(a, 0, sizeof(a));
memset(b, 0, sizeof(b));
a[len] = 1;
h = 1;
for (int i = 2; i <= n; ++i) { //高精阶乘和
jc(i);
j();
}
b[1] += 1; //注:加上剩下的1
for (int i = now_len; i >= 1; --i) //倒输
cout << b[i];
return 0;
}