C++ 中如何處理大數字?


在 C++ 中,我們可以使用 boost 庫來使用大數字。這個 C++ boost 庫是廣泛使用的庫。它用於不同的部分。它擁有大量的應用程式。例如,透過使用 boost,我們可以在 C++ 中使用 264 這樣的大數字。

在這裡,我們將看到一些 boost 庫的例子。我們可以使用 big integer 資料型別。我們可以使用不同的資料型別,比如 int128_t、int256_t、int1024_t 等。透過使用它,我們可以輕鬆地獲得高達 1024 的精度。

我們首先使用 boost 庫來乘以兩個較大的數字。

示例

#include<iostream>
#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
using namespace std;
int128_t large_product(long long n1, long long n2) {
   int128_t ans = (int128_t) n1 * n2;
   return ans;
}
int main() {
   long long num1 = 98745636214564698;
   long long num2 = 7459874565236544789;
   cout << "Product of "<< num1 << " * "<< num2 << " = " <<
   large_product(num1,num2);
}

輸出

Product of 98745636214564698 * 7459874565236544789 =
736630060025131838840151335215258722

另一種資料型別是任意的精度資料型別。因此,我們可以使用 cpp_int 資料型別來使用任意精度。它會在執行時自動分配精度。

示例

#include<iostream>
#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
using namespace std;
cpp_int large_fact(int num) {
   cpp_int fact = 1;
   for (int i=num; i>1; --i)
      fact *= i;
   return fact;
}
int main() {
   cout << "Factorial of 50: " << large_fact(50) << endl;
}

輸出

Factorial of 50:
30414093201713378043612608166064768844377641568960512000000000000

更新於:2019 年 7 月 30 日

12K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.