在C ++中处理大数字?
在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 << "乘积 "<< num1 << " * "<< num2 << " = " <<
large_product(num1,num2);
}输出结果
乘积 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 << "50阶乘: " << large_fact(50) << endl;
}输出结果
50阶乘: 30414093201713378043612608166064768844377641568960512000000000000