C/C++中int128的那點事


最近群友對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大數讀入模板:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 inline __int128 read()
 4 {
 5     __int128 x=0,f=1;
 6     char ch=getchar();
 7     while(ch<'0'||ch>'9')
 8     {
 9         if(ch=='-')
10             f=-1;
11         ch=getchar();
12     }
13     while(ch>='0'&&ch<='9')
14     {
15         x=x*10+ch-'0';
16         ch=getchar();
17     }
18     return x*f;
19 }
20 
21 inline void write(__int128 x)
22 {
23     if(x<0)
24     {
25         putchar('-');
26         x=-x;
27     }
28     if(x>9)
29         write(x/10);
30     putchar(x%10+'0');
31 }
32 
33 int main()
34 {
35     __int128 a = read();
36     __int128 b = read();
37     write(a + b);
38     return 0;
39 }

測試了一下,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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM