码迷,mamicode.com
首页 > 编程语言 > 详细

初涉算法——大整数类

时间:2017-07-21 23:14:53      阅读:271      评论:0      收藏:0      [点我收藏+]

标签:结构体   除法   name   变量   cout   idt   代码   精度   main   

  • 处理方法:用数组存储整数。
  • C++好处:重载运算符,使大整数类可以像int一样使用。

结构体BigInteger可用于储存高精度非负整数:

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<vector>
 4 #include<iostream>
 5 using namespace std;
 6 
 7 struct BigInteger {
 8   static const int BASE = 100000000;
 9   static const int WIDTH = 8;
10   vector<int> s;        //用来保存大整数的各个位数 
11 
12   BigInteger(long long num = 0) { *this = num; }    //构造函数 
13   BigInteger operator = (long long num)             //赋值运算符 
14   {
15     s.clear();
16     do {
17       s.push_back(num % BASE);
18       num /= BASE;
19     } while(num > 0);
20     return *this;
21   }
22   BigInteger operator = (const string& str)     //赋值运算符 
23   {
24     s.clear();
25     int x, len = (str.length() - 1) / WIDTH + 1;
26     for(int i = 0; i < len; i++) {
27       int end = str.length() - i*WIDTH;
28       int start = max(0, end - WIDTH);
29       sscanf(str.substr(start, end-start).c_str(), "%d", &x);
30       s.push_back(x);
31     }
32     return *this;
33   }
34   BigInteger operator + (const BigInteger& b) const {  //减法、乘法和除法的原理类似,可参考代码仓库
35     BigInteger c;
36     c.s.clear();
37     for(int i = 0, g = 0; ; i++) {
38       if(g == 0 && i >= s.size() && i >= b.s.size()) break;
39       int x = g;
40       if(i < s.size()) x += s[i];
41       if(i < b.s.size()) x += b.s[i];
42       c.s.push_back(x % BASE);
43       g = x / BASE;
44     }
45     return c;
46   }
47 };
48 
49 ostream& operator << (ostream &out, const BigInteger& x) {        //可以用cout<<的方式进行输出 
50   out << x.s.back();
51   for(int i = x.s.size()-2; i >= 0; i--) {
52     char buf[20];
53     sprintf(buf, "%08d", x.s[i]);
54     for(int j = 0; j < strlen(buf); j++) out << buf[j];
55   }
56   return out;
57 }
58 
59 istream& operator >> (istream &in, BigInteger& x) {                //可以用cin>>的方式进行输入 
60   string s;
61   if(!(in >> s)) return in;
62   x = s;
63   return in;
64 }
65 
66 #include<set>
67 #include<map>
68 set<BigInteger> s;
69 map<BigInteger, int> m;
70 
71 int main() {
72   BigInteger y;
73   BigInteger x = y;
74   BigInteger z = 123;
75   BigInteger a, b;
76   cin >> a >> b;
77   cout << a + b << "\n";
78   cout << BigInteger::BASE << "\n";            //BASE为static成员变量 
79   return 0;
80 }

 

初涉算法——大整数类

标签:结构体   除法   name   变量   cout   idt   代码   精度   main   

原文地址:http://www.cnblogs.com/xzxl/p/7219853.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!