跳到正文

算法·理论

详解__int128

FReQuenter约 6 分钟
原文
文章信息与版本

文章信息

发布
2021年12月29日
收录
2025年12月12日
更新
2026年10月28日
篇幅
约 6 分钟

版本

  1. v1当前

前言

如果遇到 long long 开不下的情况,可以使用 __int128 来博一把! note :__int128 仅 6464 位 GCCG++GCC G++ 支持,不在 C++C++ 标准中!不在 namespace std 中! 6464 位 GCCGCC 可直接使用。

存储范围

顾名思义, __int128 就是占用128字节的整数存储类型。由于是二进制,范围就是 −2127-2^{127} ~ 2127−12^{127}-1,如果使用了 unsigned __int128,则范围变成 00 ~ 21282^{128},即约39位数!

经作者实测,这样 __int128 的精确范围是 −170141183460469231731687303715884105728-170141183460469231731687303715884105728 ~ 170141183460469231731687303715884105727170141183460469231731687303715884105727

unsigned __int128 的精确范围则是 00 ~ 340282366920938463463374607431768211455340282366920938463463374607431768211455

使用方法

由于 __int128 仅仅是 GCCGCC 编译器内的东西,不在 C++98/03/11/14/17/20C++ 98/03/11/14/17/20 标准内,且仅 GCC4.6GCC4.6 以上64位版本支持,很多配套都没有,只有四则运算功能 所以要自己写输入输出。使用方法与 int long long 无异:

C++
__int128 a=9,b=27;
a=10;
a+=b;
a*=b;
... ...

输入输出

由于不在 C++C++ 标准内,没有配套的 printf scanf cin cout 输入输出,只能手写。

方法一:(对于 cin cout ):

思路:写一个类(更推荐结构体),实现快读(换一下数据),写一个返回值,将读入过程转换成一个函数。

note :此种方法用的还是 CC 的输入输出!切记不要把它和 istream ostream 混为一谈!
如果程序中关闭了同步(ios::sync_with_stdio(0);)造成输入输出混乱,后果自负!
C++
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 是不可以的!

方法二:快读、快写板子:

其实就是把快读、快写的数据类型改了一下(偷懒)

C++
#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 ………… hmmhmm ………… 那是 CC 的函数,除非你再写一个?


配套函数

如果你想赋一个 巨大无比{巨大无比} 的初值,最大只能赋值成 long long 最大值。想要 10000000000000000000000000000000000000001000000000000000000000000000000000000000 这样的数只能用字符串:

C++
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 15:38

upd on 2022/1/19

添加 cin cout 输出


另祝:Happy New Year! (In my luoguluogu blogblog)

虽然新年过了,春节不是还没到嘛?

原文
存档评论1 条抓取于