跳到正文

个人记录

浅谈__int128

Terrific_Year约 3 分钟
原文
文章信息与版本

文章信息

发布
2020年2月18日
收录
2025年12月12日
更新
2026年11月13日
篇幅
约 3 分钟
获赞
2

版本

  1. v1当前

很多时候,题目的数据范围刚好卡在long long的临界范围,经过多次运算后,最后答案就有可能会爆(例如P6101 出言不逊)。

有可能只是本蒟蒻太菜,不会用其他方法,我就偶然瞟到了有人在讨论__int128这个类型,我觉得很神奇,就自己试了试,发现:

woc,不能用cin,cout读入输出有个鬼用

于是我想到了类似于快读的好东西

读入程序如下:

C++
inline void read(__int128 &x) {
	x=0;
	int f=1;//判断正负 
	char ch=getchar();//读入字符
	while(ch<'0'||ch>'9') {
		if(ch=='-')
			f=-1;
		ch=getchar();
	}
	while(ch>='0'&&ch<='9') {//是数字就读
		x=x*10+ch-'0';//之前结果乘10,加现在读入的
		ch=getchar();
	}
	x*=f;//添上符号返回
}

输出程序如下:

C++
inline void write(__int128 x) {
	if(x<0) {
		putchar('-');//输出符号
		x=-x;
	}
	if(x>9)write(x/10);//递归输出
	putchar(x%10+'0');//输出个位
}

以下是操作实例:

C++
#include<bits/stdc++.h>
using namespace std;
inline void read(__int128 &x) {
	x=0;
	int f=1;//判断正负 
	char ch=getchar();//读入字符
	while(ch<'0'||ch>'9') {
		if(ch=='-')
			f=-1;
		ch=getchar();
	}
	while(ch>='0'&&ch<='9') {//是数字就读
		x=x*10+ch-'0';//之前结果乘10,加现在读入的
		ch=getchar();
	}
	x=x*f;//添上符号返回
}
inline void write(__int128 x) {
	if(x<0) {
		putchar('-');//输出符号
		x=-x;
	}
	if(x>9)write(x/10);//递归输出
	putchar(x%10+'0');//输出个位
}
__int128 a,b;
int main(){
	read(a);//读入a
	read(b);//读入b
	write(a+b);//输出a+b
	return 0;//完美结束
}

__int128范围是−2127≤x<2127-2^{127}≤x< 2^{127}。

那有时候条件是<21282^{128}的非负整数数怎么办?

那就加个unsigned呀!

直接讲实例了:

C++
#include<bits/stdc++.h>
using namespace std;
inline void read(unsigned __int128 &x) {
	x=0; 
	char ch=getchar();//读入字符
	while(ch>='0'&&ch<='9') {//是数字就读
		x=x*10+ch-'0';//之前结果乘10,加现在读入的
		ch=getchar();
	}
	//已经读完 
}
inline void write(unsigned __int128 x) {
	if(x>9)write(x/10);//递归输出
	putchar(x%10+'0');//输出个位
}
unsigned __int128 a,b;//无符号整型
int main(){
	read(a);//读入a
	read(b);//读入b
	write(a+b);//输出a+b
	return 0;//完美结束
}

但是大家要注意,尽量少用,因为内存占得很多