ในปัญหานี้ เราจำเป็นต้องสร้างโปรแกรมเพื่อค้นหาค่าสูงสุดของจำนวนเต็มที่สามารถคำนวณแฟคทอเรียลบนเครื่องในภาษา C++
แฟกทอเรียลของตัวเลขมีค่ามาก เนื่องจากเป็นผลคูณของค่าทั้งหมดที่อยู่ข้างหน้า และ C ++ สามารถจัดการค่าขนาดใหญ่ได้ไม่เกินค่าที่กำหนดโดยใช้ฟังก์ชัน inbuilt เราต้องหาข้อจำกัดนี้ให้ได้
แนวทางการแก้ปัญหา
เราจะใช้คุณสมบัติของประเภทข้อมูลอย่างง่าย ๆ ซึ่งก็คือเมื่อตัวเลขเกินค่าสูงสุดจะส่งกลับจำนวนลบ
เราจะใช้ 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