前言
如果遇到 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;
... ...
輸入輸出
由於不在 \(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
添加
cin
cout
輸出
另祝:Happy New Year! (In my \(luogu\) \(blog\))
雖然新年過了,春節不是還沒到嘛?