在 C++ 中处理大数?

c++server side programmingprogramming更新于 2025/4/22 18:22:17

在 C++ 中,我们可以使用 boost 库来处理大数。这个 C++ boost 库是一个广泛使用的库。它用于不同的部分。它具有广泛的应用领域。例如,使用 boost,我们可以在 C++ 中使用像 264 这样的大数。

这里我们将看到一些 boost 库的示例。我们可以使用大整数数据类型。我们可以使用不同的数据类型,如 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

相关文章