Thư viện Boost C++ là một tập hợp thư viện mạnh mẽ, được sử dụng rộng rãi trong nhiều lĩnh vực khác nhau. Một trong những ứng dụng nổi bật là khả năng xử lý các số nguyên lớn vượt quá giới hạn của các kiểu dữ liệu cơ bản.
Sử dụng kiểu dữ liệu số nguyên lớn (Big Integer)
Boost cung cấp các kiểu dữ liệu như int128_t, int256_t, int1024_t cho phép tính toán chính xác đến 1024 bit. Dưới đây là ví dụ nhân hai số lớn:
Ví dụ: Nhân số lớn với int128_t
#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);
}
Kết quả
Product of 98745636214564698 * 7459874565236544789 = 736630060025131838840151335215258722
Kiểu dữ liệu độ chính xác tùy ý (Arbitrary Precision) - cpp_int
Kiểu cpp_int tự động điều chỉnh độ chính xác tại thời điểm chạy, phù hợp cho tính toán giai thừa lớn:
Ví dụ: Tính giai thừa 50!
#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;
}
Kết quả
Factorial of 50: 30414093201713378043612608166064768844377641568960512000000000000
Số thực độ chính xác cao (Multiprecision Float)
Sử dụng cpp_dec_float_50 hoặc cpp_dec_float_100 để đạt độ chính xác 50 hoặc 100 chữ số thập phân:
Ví dụ: Tính diện tích hình tròn với độ chính xác cao
#include <iostream>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/math/constants/constants.hpp>
#include <iomanip>
#include <limits>
using boost::multiprecision::cpp_dec_float_50;
using namespace std;
template <typename T>
inline T circle_area(T r) {
using boost::math::constants::pi;
return pi<T>() * r * r;
}
int main() {
float f_rad = 243.0 / 100;
float f_area = circle_area(f_rad);
double d_rad = 243.0 / 100;
double d_area = circle_area(d_rad);
cpp_dec_float_50 rad_mp = 243.0 / 100;
cpp_dec_float_50 area_mp = circle_area(rad_mp);
cout << "Float: " << setprecision(numeric_limits<float>::digits10) << f_area << endl;
cout << "Double: " << setprecision(numeric_limits<double>::digits10) << d_area << endl;
cout << "Boost Multiprecision Res: " << setprecision(numeric_limits<cpp_dec_float_50>::digits10) << area_mp << endl;
}
Kết quả
Float: 18.5508 Double: 18.5507904601824 Boost Multiprecision Res: 18.550790460182372534747952560288165408707655564121