阶乘之和 (大数加法+大数乘法)

阶乘之和

题目描述

用高精度计算出S=1!+2!+3!+…+n!(n ≤ 50)其中“!”表示阶乘,例如:5!=5*4*3*2*1。

输入描述:

输入正整数N

输出描述:

输出计算结果S

示例1

输入

3

输出

9

 

思路:这里直接用两个自己写的大数运算的函数,模拟手写加法和乘法解决。

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<cmath>
 5 #include<algorithm>
 6 #include<map>
 7 #include<set>
 8 #include<vector>
 9 #include<queue>
10 #include<list>
11 #include<unordered_map>
12 using namespace std;
13 #define ll long long 
14 const int inf=1e9+7;
15 const int mod=1e9+7;
16 
17 //const int maxn=
18 
19 inline string sum(string a,string b)//大数加法 
20 {
21     while(a.size()<b.size())
22         a.insert(0,"0");
23     while(b.size()<a.size())
24         b.insert(0,"0");
25     string ans="";
26     int jinwei=0,sum,yu;
27     for(int i=a.size()-1;i>=0;i--)
28     {
29         sum=(a[i]-'0')+(b[i]-'0')+jinwei;
30         jinwei=sum/10;
31         yu=sum%10;
32         ans+=(yu+'0');
33     }
34     if(jinwei)
35         ans+=(jinwei+'0');
36     reverse(ans.begin(),ans.end());
37     return ans;
38 }
39 
40 inline string mul(string a,string b)//大数乘法 
41 {
42     if(a.size()<b.size())
43         swap(a,b);
44     string ans="0",res;
45     char now;
46     for(int i=b.size()-1;i>=0;i--)
47     {
48         res="";
49         now=b[i];    
50         int jinwei=0,yu,s;    
51         for(int j=a.size()-1;j>=0;j--)
52         {
53             s=(now-'0')*(a[j]-'0')+jinwei;
54             jinwei=s/10;
55             yu=s%10;
56             res+=(yu+'0');
57         }
58         if(jinwei)
59             res+=(jinwei+'0');    
60             
61         reverse(res.begin(),res.end());//从余数加起,结果是反的,需逆置 
62         
63         for(int j=0;j<b.size()-i-1;j++)//高位相乘运算之后末尾加0 
64             res+="0";    
65         ans=sum(ans,res);//再相加 
66     }
67     return ans;
68 }
69 
70 int main()
71 {
72     ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
73     int n;
74     while(cin>>n)
75     {
76         string ans="0";
77         string s="1";
78         for(int i=1;i<=n;i++)//阶乘之和 
79         {
80             s=mul(s,to_string(i));
81             ans=sum(ans,s);
82         }
83         cout<<ans<<endl;
84     }
85     return 0;
86 }
大佬见笑,,
原文地址:https://www.cnblogs.com/xwl3109377858/p/11281584.html