用高精度计算出 S=1!+2!+3!+⋯+n!(n≤50)。
其中!表示阶乘,定义为 n!=n×(n−1)×(n−2)×⋯×1。例如,5!=5×4×3×2×1=120。
输入格式
一个正整数 n。
输出格式
一个正整数 S,表示计算结果。
输入输出样例
输入 #1复制
3
输出 #1复制
9
说明/提示
【数据范围】
对于 100% 的数据,1≤n≤50。
我第一次是这样写的
#include<bits/stdc++.h>
using namespace std;
int a[10];
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin>>n;
int sum=1,ans=0;
for(int i=1;i<=n;i++){
sum=1; // 每次重新初始化阶乘
for(int j=1;j<=i;j++){ sum*=j; // 算出 i! }
ans+=sum; // 累加进总和
}
cout<<ans;
return 0;
}
提交半天发现满分不了
才发现是这样写的
#include<bits/stdc++.h>
using namespace std;
int jiecheng[300];
int he[300];
void chengfa(int cnt){
int jinwei=0;
for(int i=1;i<=jiecheng[0];i++){
int temp=jiecheng[i]*cnt+jinwei;
jiecheng[i]=temp%10;
jinwei=temp/10;
}
if(jinwei>0){
while(jinwei>0){
jiecheng[++jiecheng[0]]=jinwei%10;
jinwei/=10;
}
}
}
void jiafa(){
int jinwei=0;
int len=max(he[0],jiecheng[0]);
for(int i=1;i<=len;i++){
int temp=he[i]+jiecheng[i]+jinwei;
he[i]=temp%10;
jinwei=temp/10;
}
he[0]=len;
if(jinwei>0){
he[++he[0]]=jinwei;
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin>>n;
jiecheng[0]=1;
jiecheng[1]=1;
he[0]=0;
for(int i=1;i<=n;i++){
if(i>1){
chengfa(i);
}
jiafa();
}
for(int i=he[0];i>=1;i--){
cout<<he[i];
}
return 0;
}