大整数模板

 1 struct BigInt{
 2     static const int MAXLEN = 200;
 3     static const int BASE = 10000;
 4     static const int WIDTH = 4;
 5     int s[MAXLEN/4], size;
 6 
 7     BigInt(const LL num = 0);
 8     BigInt & operator=(const LL num);
 9     BigInt & operator=(const string &str);
10     BigInt operator+(const BigInt &rhs) const;
11     BigInt operator*(const BigInt &rhs) const;
12     bool read();
13     void print();
14 };
15 
16 BigInt::BigInt(const LL num){
17     *this = num;
18 }
19 
20 BigInt & BigInt::operator=(LL num){
21     memset(s, 0, sizeof(s));
22     size = 0;
23     do{
24         s[size++] = num % BASE;
25         num /= BASE;
26     }while(num > 0);
27     return *this;
28 }
29 
30 BigInt& BigInt::operator=(const string& rhs){
31     memset(s, 0, sizeof(s));
32     size = 0;
33     int x, len = (rhs.length() - 1) / WIDTH + 1;
34     for(int i = 0; i < len; i++){
35         int end= rhs.length() - i * WIDTH;
36         int start = max(0, end - WIDTH);
37         sscanf(rhs.substr(start, end - start).c_str(), "%d", &x);
38         s[size++] = x;
39     }
40     return *this;
41 }
42 
43 BigInt BigInt::operator+(const BigInt & rhs) const{
44     BigInt ret;
45     memset(ret.s, 0, sizeof(s));
46     ret.size = 0;
47     for(int i = 0, x = 0; ; i++){
48         if(x == 0 && i >= size && i >= rhs.size) break;
49         if(i < size) x += s[i];
50         if(i < rhs.size) x += rhs.s[i];
51         ret.s[ret.size++] = x % BASE;
52         x /= BASE;
53     }
54     return ret;
55 }
56 
57 BigInt BigInt::operator*(const BigInt & rhs)const{
58     BigInt ret;
59     memset(ret.s, 0, sizeof(s));
60     ret.size = 0;
61     for(int i = 0; i < size; i++){
62         int carry = 0;
63         for(int j = 0; j < rhs.size; j++){
64             ret.s[i + j] += s[i] * rhs.s[j] + carry;
65             if(ret.s[i + j] >= BASE){
66                 carry = ret.s[i + j] / BASE;
67                 ret.s[i + j] %= BASE;
68             }
69             else carry = 0;
70         }
71         if(carry){
72             ret.s[i + rhs.size] = carry;
73         }
74     }
75     while(ret.s[ret.size - 1] == 0 && ret.size > 1)
76         ret.size--;
77     return ret;
78 }
79 
80 bool BigInt::read(){
81     char buf[MAXLEN];
82     if(scanf("%s", buf) == EOF)
83         return false;
84     string s(buf);
85     *this = s;
86     return true;
87 }
88 
89 void BigInt::print(){
90     printf("%d", s[size - 1]);
91     for(int i = size - 2; i >= 0; i--){
92         printf("%04d", s[i]);
93     }
94 }

 

posted @ 2017-08-15 00:19  Sissi_hss  阅读(128)  评论(0编辑  收藏  举报