最近群友(人家的)对int128
这个东西讨论的热火朝天的。讲道理的话,编译器的gcc是不支持__int128
这种数据类型的,比如在\(codeblocks 16.01/Dev C++\)是无法编译的,但是提交到大部分\(OJ\)上是可以编译且能用的。C/C++标准。IO是不认识__int128
这种数据类型的,因此要自己实现IO
,其他的运算,与int
没有什么不同。
但是官方上写了\(GCC\)提供了两种128位整数类型,分别是__int128_t
和__uint128_t
,分别用于声明有符号整数变量和无符号整数变量。
有关GCC的文档参见:Using the GNU Compiler Collection (GCC)。
这里给出了样例程序,是有关类型__int128_t
和__uint128_t
的。从计算可以看出,这两个类型都是\(16\)字节的,类型__uint128_t
是\(128\)位的。程序中使用了按位取反运算,移位运算和乘法运算。
由于这种大整数无法使用函数printf()
输出其值,所以自己(人家)做了一个整数转字符串函数myitoa()
,用于实现128位整数的输出。
有兴趣的同学(没兴趣)想了解底层实现原理可以参看我(人家的)的Github上:https://github.com/AngelKitty/English-Version-CHSInt128
代码实现如下:
1 #include <iostream>
2
3 using namespace std;
4
5 void myitoa(__int128_t v, char* s)
6 {
7 char temp;
8 int i=0, j;
9
10 while(v >0) {
11 s[i++] = v % 10 + '0';
12 v /= 10;
13 }
14 s[i] = '\0';
15
16 j=0;
17 i--;
18 while(j < i) {
19 temp = s[j];
20 s[j] = s[i];
21 s[i] = temp;
22 j++;
23 i--;
24 }
25 }
26
27 int main()
28 {
29 __uint128_t n = 0;
30
31 n = ~n;
32 int count = 0;
33 while(n > 0) {
34 count++;
35 n >>= 1;
36 }
37
38 cout << "count=" << count << endl;
39 cout << "__uint128_t size=" << sizeof(__uint128_t) << endl;
40 cout << endl;
41
42 cout << "__int128_t size=" << sizeof(__int128_t) << endl;
43
44 __int128_t x = 1100000000000000L;
45 __int128_t y = 2200000000000000L;
46 char s[40];
47
48 x *= y;
49
50 myitoa(x, s);
51
52 cout << "x=" << s << endl;
53
54 return 0;
55 }
打印结果如下:
count=128
__uint128_t size=16
__int128_t size=16
x=2420000000000000000000000000000
以下是__int128
的\(OJ\)简单应用,写题必备神器。
a+b
大数读入模板:
#include <bits/stdc++.h>
using namespace std;
inline __int128 read(){
__int128 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*10+ch-'0';
ch=getchar();
}
return x*f;
}
inline void print(__int128 x){
if(x<0){
putchar('-');
x=-x;
}
if(x>9)
print(x/10);
putchar(x%10+'0');
}
int main(void){
__int128 a = read();
__int128 b = read();
print(a + b);
return 0;
}
测试了一下,\(OJ\)提交没问题~~~
另外关于\(C/C++\)大数类,这里还给您(不是我)提供了一个好的实现机制,源码我已经上传,下载链接在这里:\(https://files.cnblogs.com/files/ECJTUACM-873284962/bigint-10-2-src.7z\)
运行结果可以看到如下所示:
\(C++ BigInt class that enables the user to work with arbitrary precision integers.\)
\(Latest Version: 10.2\)
Project Samples
作 者(不是我):\(Angel_Kitty\)