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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP