高精度集合


高精度

c++中,最大的整数范围也只有unsigned long long\(2^{64}-1\)

数据类型 最小值 最大值
unsigned int 0 4294967295 (\(2^{32} - 1\))
int -2147483648 2147483647 (\(2^{31} - 1\))
unsigned long 0 4294967295 (\(2^{32} - 1\))
long -2147483648 2147483647 (\(2^{31} - 1\))
unsigned long long 0 18446744073709551615 (\(2^{64} - 1\))
long long -9223372036854775808 9223372036854775807 (\(2^{63} - 1\))

所以,在算法竞赛中,遇到更大的数,就要用到高精度了。

高精度算法(High Accuracy Algorithm)是处理大数字的数学计算方法。在一般的科学计算中,会经常算到小数点后几百位或者更多,当然也可能是几千亿几百亿的大数字。一般这类数字我们统称为高精度数,高精度算法是用计算机对于超大数据的一种模拟加,减,乘,除,乘方,阶乘,开方等运算。对于非常庞大的数字无法在计算机中正常存储,于是,将这个数字拆开,拆成一位一位的,或者是四位四位的存储到一个数组中, 用一个数组去表示一个数字,这样这个数字就被称为是高精度数。高精度算法就是能处理高精度数各种运算的算法,但又因其特殊性,故从普通数的算法中分离,自成一家。

当然,Python中就不存在高精度了,因为Python内置!QWQ
紫书中写了一个高精度类,我把它放在这里,方便使用。

#include
#include
#include
#include
using namespace std;

struct BigInteger {
  static const int BASE = 100000000;
  static const int WIDTH = 8;
  vector s;

  BigInteger(long long num = 0) { *this = num; } // 构造函数
  BigInteger operator = (long long num) { // 赋值运算符
    s.clear();
    do {
      s.push_back(num % BASE);
      num /= BASE;
    } while(num > 0);
    return *this;
  }
  BigInteger operator = (const string& str) { // 赋值运算符
    s.clear();
    int x, len = (str.length() - 1) / WIDTH + 1;
    for(int i = 0; i < len; i++) {
      int end = str.length() - i*WIDTH;
      int start = max(0, end - WIDTH);
      sscanf(str.substr(start, end-start).c_str(), "%d", &x);
      s.push_back(x);
    }
    return *this;
  }
  BigInteger operator + (const BigInteger& b) const {
    BigInteger c;
    c.s.clear();
    for(int i = 0, g = 0; ; i++) {
      if(g == 0 && i >= s.size() && i >= b.s.size()) break;
      int x = g;
      if(i < s.size()) x += s[i];
      if(i < b.s.size()) x += b.s[i];
      c.s.push_back(x % BASE);
      g = x / BASE;
    }
    return c;
  }
};

ostream& operator << (ostream &out, const BigInteger& x) {
  out << x.s.back();
  for(int i = x.s.size()-2; i >= 0; i--) {
    char buf[20];
    sprintf(buf, "%08d", x.s[i]);
    for(int j = 0; j < strlen(buf); j++) out << buf[j];
  }
  return out;
}

istream& operator >> (istream &in, BigInteger& x) {
  string s;
  if(!(in >> s)) return in;
  x = s;
  return in;
}

#include
#include
set s;
map m;

int main() {
  BigInteger y;
  BigInteger x = y;
  BigInteger z = 123;

  BigInteger a, b;
  cin >> a >> b;
  cout << a + b << "\n";
  cout << BigInteger::BASE << "\n";
  return 0;
}