高精度模板

这个模板不是我敲得,而是老师敲得T_T(懒得敲。。。。

  1 #include<iostream>
  2 #include<cstdio>
  3 #include<cstring>
  4 #include<algorithm>
  5 #include<cmath>
  6 #include<cstdlib>
  7 #include<ctime>
  8 #include<string>
  9 using namespace std;
 10 
 11 
 12 
 13 struct bignum
 14 {
 15     int n;
 16     int a[500];
 17     bignum()
 18     {
 19         n = 0;
 20         memset(a, 0, sizeof(a));
 21     }
 22         
 23     bignum(string s)
 24     {
 25         n = s.size();
 26         memset(a, 0, sizeof(a));
 27         for (int i = 0; i < n; i++)
 28             a[i] = s[n - 1 -i] -'0';
 29     }
 30     bignum(int s)
 31     {
 32         memset(a, 0, sizeof(a));
 33         n = 0;
 34         while (s > 0)
 35         {
 36             a[n] = s % 10;
 37             s /= 10;
 38             n++;
 39         }
 40     }
 41     void work()
 42     {
 43         for (int i = 0; i < n; i++)
 44         {
 45             if (a[i] < 0)
 46             {
 47                 int tmp = (-a[i] - 1) / 10 + 1;
 48                 a[i] += 10 * tmp;
 49                 a[i + 1] -= tmp;
 50             }
 51             if (a[i] >= 10)
 52             {
 53                 int tmp = a[i] / 10;
 54                 a[i] -= 10* tmp;
 55                 a[i + 1] += tmp;
 56                 if (i == n - 1 && a[i + 1] > 0) n++;
 57             }
 58         }
 59         while (n > 0 && a[n - 1] == 0) n--;
 60     }
 61     void print()
 62     {
 63         for (int i = n - 1; i >= 0; i--)
 64             cout << a[i];
 65         cout << endl;
 66     }
 67 };
 68 
 69 bignum operator + (const bignum &a, const bignum &b)
 70 {
 71     bignum c;
 72     c.n = max(a.n, b.n);
 73     for (int i = 0; i < c.n; i++)
 74         c.a[i] = a.a[i] + b.a[i];
 75     c.work();
 76     return c;
 77 }
 78 
 79 
 80 bignum operator - (const bignum &a, const bignum &b)
 81 {
 82     bignum c;
 83     c.n = max(a.n, b.n);
 84     for (int i = 0; i < c.n; i++)
 85         c.a[i] = a.a[i] - b.a[i];
 86     c.work();
 87     return c;
 88 }
 89 
 90 
 91 bignum operator * (const bignum &a, const bignum &b)
 92 {
 93     bignum c;
 94     c.n = a.n + b.n - 1;
 95     for (int i = 0; i < a.n; i++)
 96         for (int j = 0; j < b.n; j++)
 97             c.a[i + j] += a.a[i] * b.a[j];
 98     c.work();
 99     return c;
100 }
101 
102 
103 int main()
104 {
105     string s;
106     cin >> s;
107     int x;
108     cin >> x;
109     bignum a(s);
110     bignum b(x);
111     (a + b).print();
112     (a - b).print();
113     (a * b).print();
114     return 0;
115 }

猜你喜欢

转载自www.cnblogs.com/tpgzy/p/8998679.html