P1009 [NOIP1998 普及组] 阶乘之和

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. const int N = 1e3 + 10;
  4. struct Bigint{
  5. int len, a[N];
  6. Bigint(int x = 0){
  7. memset(a, 0, sizeof a);
  8. len = 0;
  9. if (x == 0) len = 1;
  10. while (x){
  11. a[len++] = x % 10;
  12. x /= 10;
  13. }
  14. }
  15. int &operator[](int i){
  16. return a[i];
  17. }
  18. void flatten(int L){
  19. len = L;
  20. for (int i = 0; i < len; i++){
  21. a[i + 1] += a[i] / 10;
  22. a[i] %= 10;
  23. }
  24. while (a[len] == 0 && len > 0) len--;
  25. len++;
  26. }
  27. void print(){
  28. for (int i = len - 1; i >= 0; i--) printf("%d", a[i]);
  29. puts("");
  30. }
  31. };
  32. Bigint operator+(Bigint a, Bigint b){
  33. Bigint c;
  34. int len = max(a.len, b.len);
  35. for (int i = 0; i < len; i++) c[i] += a[i] + b[i];
  36. c.flatten(len + 1);
  37. return c;
  38. }
  39. Bigint operator*(Bigint a, int b){
  40. Bigint c;
  41. int len = a.len;
  42. for (int i = 0; i < len; i++) c[i] = a[i] * b;
  43. c.flatten(len + 500);
  44. return c;
  45. }
  46. int main(){
  47. Bigint ans(0), fac(1);
  48. int n;
  49. cin >> n;
  50. for (int i = 1; i <= n; i++){
  51. fac = fac * i;
  52. ans = ans + fac;
  53. }
  54. ans.print();
  55. return 0;
  56. }
  1. 大整数运算,使用vector<>实现