long long 不够用?详解 __int128
前言
如果遇到 long long 开不下的情况,可以使用 __int128 来博一把!
note :__int128 仅 \(64\) 位 \(GCC G++\) 支持,不在 \(C++\) 标准中!不在 namespace std 中!
\(64\) 位 \(GCC\) 可直接使用。
存储范围
顾名思义, __int128 就是占用128字节的整数存储类型。由于是二进制,范围就是 \(-2^{127}\) ~ \(2^{127}-1\),如果使用了 unsigned __int128,则范围变成 \(0\) ~ \(2^{128}\),即约39位数!
经作者实测,这样 __int128 的精确范围是
\(-170141183460469231731687303715884105728\) ~ \(170141183460469231731687303715884105727\)
unsigned __int128 的精确范围则是 \(0\) ~ \(340282366920938463463374607431768211455\)
使用方法
由于 __int128 仅仅是 \(GCC\) 编译器内的东西,不在 \(C++ 98/03/11/14/17/20\) 标准内,且仅 \(GCC4.6\) 以上64位版本支持,很多配套都没有,只有四则运算功能 所以要自己写输入输出。使用方法与 int long long 无异:
__int128 a=9,b=27;
a=10;
a+=b;
a*=b;
... ...
事实上,对于赋值,直接令 __int128 x=1e36 这一类也是可以的,但是 __int128 x=1e36+1 这样使用要非常小心,浮点数可能会掉精度。
输入输出
由于不在 \(C++\) 标准内,没有配套的 printf scanf cin cout 输入输出,只能手写。
方法一:(对于 cin cout ):
思路:写一个类(更推荐结构体),实现快读(换一下数据),写一个返回值,将读入过程转换成一个函数。
note :此种方法用的还是 \(C\) 的输入输出!切记不要把它和 istream ostream 混为一谈!
如果程序中关闭了同步(ios::sync_with_stdio(0);)造成输入输出混乱,后果自负!
namespace fastio{
struct reader{
template<typename T>Reader&operator>>(T&x){
char c=getchar();short f=1;
while(c<'0'||c>'9'){if(c=='-')f*=-1;c=getchar();}
x=0;while(c>='0'&&c<='9'){
x=(x<<1)+(x<<3)+(c^48);
c=getchar();
}x*=f;return *this;
}
}cin;
struct writer{
template<typename T>Writer&operator<<(T x){
if(x==0)return putchar('0'),*this;
if(x<0)putchar('-'),x=-x;
static int sta[45];int top=0;
while(x)sta[++top]=x%10,x/=10;
while(top)putchar(sta[top]+'0'),--top;
return*this;
}
}cout;
};
#define cin fastio::cin
#define cout fastio::cout
在程序的最上面(头文件下第二行,using namespace std后)加入此代码,就可以使用 cin cout 输入输出 __int128 啦!
note :这是自己写的 cin cout ,用std::cin std::cout 是不可以的!
方法二:快读、快写板子:
其实就是把快读、快写的数据类型改了一下(偷懒)
#define int __int128
inline void read(int &n){
int x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9'){
if(ch=='-') f=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9'){
x=(x<<1)+(x<<3)+(ch^48);
ch=getchar();
}
n=x*f;
}
inline void print(int n){
if(n<0){
putchar('-');
n*=-1;
}
if(n>9) print(n/10);
putchar(n % 10 + '0');
}
#undef int
至于 printf scanf \(……\) \(hmm\) \(……\) 那是 \(C\) 的函数,除非你再写一个?
配套函数
如果你想赋一个 \({巨大无比}\) 的初值,最大只能赋值成 long long 最大值。想要 \(1000000000000000000000000000000000000000\) 这样的数只能用字符串:
inline __int128 to_int128(string s){
int l=s.length();
__int128 m=0;
for(int i=0;i<l;i++){
m*=10;
m+=s[i]-48;
}
return m;
}
END.
2021/12/31
upd on 2022/1/19
添加
cincout输出
另祝:Happy New Year! (In my \(luogu\) \(blog\))
虽然新年过了,春节不是还没到嘛?

浙公网安备 33010602011771号