ในปัญหานี้ เราต้องสร้างโปรแกรมเพื่อหาค่าสูงสุดของจำนวนเต็มที่คำนวณแฟกทอเรียลได้บนเครื่องใน C++
แฟกทอเรียลของจำนวนเป็นค่าที่ใหญ่มาก เนื่องจากเป็นผลคูณของทุกค่าที่นำหน้า它 C++ สามารถจัดการค่าขนาดใหญ่ได้ فقطจนถึงค่าหนึ่งด้วยฟังก์ชันในตัว (inbuilt) เราต้องหาขีดจำกัดนี้
แนวทางแก้ปัญหา
เราจะใช้คุณสมบัติของชนิดข้อมูล (data types) ซึ่งคือเมื่อตัวเลขเกินค่าสูงสุด จะคืนค่าติดลบ
เราจะใช้ long long int ซึ่งเป็นชนิดข้อมูลพื้นฐานที่ใหญ่ที่สุด
ตัวอย่างโค้ด
#include <iostream>
using namespace std;
int calcMaxFactVal() {
int maxVal = 1;
long long int maxFactorial = 1;
while (true) {
if (maxFactorial < 0)
return (maxVal - 1);
maxVal++;
maxFactorial *= maxVal;
}
return -1;
}
int main() {
cout << "The maximum value of an integer for which factorial can be calculated on machine is " << calcMaxFactVal();
return 0;
}
ผลลัพธ์
The maximum value of an integer for which factorial can be calculated on machine is 20