Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

การจัดการจำนวนมากใน C ++?


ใน C ++ เราสามารถใช้ตัวเลขจำนวนมากได้โดยใช้ไลบรารีบูสต์ ไลบรารีบูสต์ C ++ นี้เป็นไลบรารีที่ใช้กันอย่างแพร่หลาย ใช้สำหรับส่วนต่างๆ มีโดเมนแอปพลิเคชันขนาดใหญ่ เช่น การใช้บูสต์ เราสามารถใช้ตัวเลขจำนวนมากได้ เช่น 2 64 ในภาษา C++

เราจะมาดูตัวอย่างบางส่วนของ Boost Library เราสามารถใช้ประเภทข้อมูลจำนวนเต็มขนาดใหญ่ได้ เราสามารถใช้ประเภทข้อมูลต่างๆ เช่น int128_t, int256_t, int1024_t เป็นต้น เมื่อใช้สิ่งนี้ เราจะได้รับความแม่นยำสูงสุด 1024 อย่างง่ายดาย

ตอนแรกเรากำลังคูณสองจำนวนมหาศาลโดยใช้ไลบรารีบูสต์

ตัวอย่าง

#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

ประเภทข้อมูลอีกประเภทหนึ่งคือ Arbitrary Precision Datatype ดังนั้นเราจึงสามารถใช้ความแม่นยำใดๆ โดยใช้ประเภทข้อมูล 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