luogu P1009 阶乘之和 高精度

题目链接:https://www.luogu.org/problemnew/show/P1009
题目大意:求 S = 1 ! + 2 ! + . . . + n ! S=1!+2!+...+n!


#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 100000 + 10;
int a[maxn],an[maxn],bn[maxn];
int n;

string fac(int n){
	if(n == 0) return "1";
	memset(a, 0, sizeof a);
	int tmp = n, len = 0;
	while(tmp) a[len++] = tmp % 10, tmp /= 10;   //将n放进数组中

	for(int i = n-1; i >= 2; i--){
		int c = 0;  //进位
		for(int j = 0;j < len; j++) a[j] = a[j] * i + c, c = a[j] / 10, a[j] %= 10;
		while(c) a[len++] = c % 10, c /= 10;
	}
	string res="";
	for(int i = 0; i < len; i++)
		res+=a[len-i-1] +'0';
	return res;
}
string add(string a,string b){
	memset(an, 0, sizeof an),memset(bn, 0,sizeof bn);
	int lena = a.length(),lenb = b.length();
	for(int i = 0;i < lena; i++) an[lena-i-1] = a[i] - '0';
	for(int i = 0;i < lenb; i++) bn[lenb-i-1] = b[i] - '0';
	int len = max(lena,lenb);
	for(int i = 0;i < len; i++){
		an[i]+=bn[i]; an[i+1] +=an[i]/10; an[i] %= 10;
	}
	if(an[len]) len++;
	string res="";
	for(int i=0;i<len;i++){
		res+=an[len-1-i]+'0';
	}
	return res;
}
int main()
{
	string res="0";
	cin>>n;
	while(n){
		res=add(res,fac(n));
		n--;
	}
	cout<<res<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Mr_HCW/article/details/88822856
今日推荐