ybt1173 阶乘和(NOIP1998普及组第2题)
时空限制 1000ms/64MB
题目描述
用高精度计算出S=1!+2!+3!+…+n!(n≤100),其中“!”表示阶乘,例如:5!=5*4*3*2*1。输入正整数n,输出计算结果S。
输入
一个正整数n。
输出
计算结果S。
输入样例
5
输出样例
153
代码
法一:数组模拟
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 205;
int n,a[N],b[N];
void fact(int n,int a[],int b[]){
memset(a,0,sizeof(int)*N);
memset(b,0,sizeof(int)*N);
a[0] = a[1] = 1;
for (int i=1; i<=n; ++i){
for (int j=1; j<=a[0]; ++j) a[j]*=i;
for (int j=1; j<=a[0]; ++j)
a[j+1]+=a[j]/10,a[j]%=10;
while (a[a[0]+1]){
a[0]++;
a[a[0]+1] += a[a[0]]/10;
a[a[0]] %= 10;
}
b[0] = max(a[0],b[0]);
for (int j=1; j<=b[0]; ++j){
b[j] += a[j];
b[j+1] += b[j]/10;
b[j] %= 10;
}
if (b[b[0]+1]) b[0]++;
}
}
void output(int a[]){
for (int i=a[0]; i>=1; --i) cout<<a[i];
cout<<'\n';
}
int main(){
cin>>n;
fact(n,a,b);
output(b);
return 0;
}
法二:重载运算符
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 205;
struct bign{
int len,d[N];
bign(){ memset(d,0,sizeof(d)); len=1; } //构造函数,默认初始化
bign(int x){ //构造函数,int初始化
memset(d,0,sizeof(d));
len = 0;
do {
d[++len] = x%10;
x /= 10;
} while (x);
}
bign operator * (const int &b){ //重载* 高*低
bign c; //c=结构体本身*b
c.len = len;
for (int i=1; i<=len; ++i) c.d[i]=d[i]*b;
for (int i=1; i<=len; ++i)
c.d[i+1]+=c.d[i]/10,c.d[i]%=10;
while (c.d[c.len+1]){
c.len++;
c.d[c.len+1] += c.d[c.len]/10;
c.d[c.len] %= 10;
}
return c;
}
bign operator *= (const int &b){ //重载*=
*this = *this*b;
return *this;
}
bign operator + (const bign &b){ //重载+ 高+高
bign c; //c=结构体本身+b
c.len = max(len,b.len);
for (int i=1; i<=c.len; ++i){
c.d[i] += d[i]+b.d[i];
c.d[i+1] += c.d[i]/10;
c.d[i] %= 10;
}
if (c.d[c.len+1]) c.len++;
return c;
}
bign operator += (const bign &b){ //重载+=
*this = *this+b;
return *this;
}
friend ostream& operator << (ostream& output,const bign &x){//重载输出流
for (int i=x.len; i>=1; --i) cout<<x.d[i];
return output;
}
};
int main(){
int n;
cin>>n;
bign f=1,sum=0; //int初始化
for (int i=1; i<=n; ++i){
f *= i; //需重载高*低、*=
sum += f; //需重载高+高、+=
}
cout<<sum<<'\n'; //需重载输出流
return 0;
}