zoukankan      html  css  js  c++  java
  • 大整数类概述

    一、相关介绍

    大数运算

    • 因数和结果可达几十万位
    • 处理方法:用数组存储和表示大数
    • C++好处:重载运算符,使大整数类可以像int一样使用

    备注:C++中的内置类型的精度最多只有20几位。

    结构体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 << "
    ";
    78   cout << BigInteger::BASE << "
    ";            //BASE为static成员变量 
    79   return 0;
    80 }
  • 相关阅读:
    Codeforces Round #171 (Div. 2)
    ACdream 1079 郭式树
    HDOJ 1517 博弈论
    ACdream 1080 面面数
    博弈论 Nim 博弈
    Codeforces Round #172 (Div. 2)
    ACdream 1084 同心树
    STL bitset
    博弈论 bash博弈
    POJ 3261 后缀数组
  • 原文地址:https://www.cnblogs.com/xzxl/p/7219853.html
Copyright © 2011-2022 走看看