เราได้รับช่วง start และ end งานคือการนับว่ามีจำนวนแฟกทอเรียล (ค่าของ n!) กี่ค่าที่อยู่ในช่วงนั้น
ตัวอย่าง
Input − start = 5, end = 600 Output − 3
คำอธิบาย − แฟกทอเรียลในช่วง: 3!=6, 4!=24, 5!=120 (6! = 720 > 600)
Input − start = 1, end = 100 Output − 5
คำอธิบาย − 0!=1, 1!=1, 2!=2, 3!=6, 4!=24 (5! = 120 > 100)
แนวทางการแก้ปัญหา
- หาแฟกทอเรียลแรกที่ ≥ start โดยคูณทีละ 1, 2, 3...
- จากนั้นนับต่อไปจนกว่าแฟกทอเรียลจะ > end
- ใช้ตัวแปร fact เก็บค่าแฟกทอเรียลปัจจุบัน, i เก็บตัวคูณถัดไป
ตัวอย่างโค้ด C++
#include <iostream>
using namespace std;
int countFactorialsInRange(int start, int end) {
int fact = 1, i = 1;
while (fact < start) {
fact *= i;
i++;
}
int count = 0;
while (fact <= end) {
count++;
fact *= i;
i++;
}
return count;
}
int main() {
int start = 5, end = 600;
cout << "Count of factorials: " << countFactorialsInRange(start, end);
return 0;
}
ผลลัพธ์
Count of factorials: 3
บทความนี้อธิบายวิธีนับค่าแฟกทอเรียล (n!) ที่อยู่ในช่วงที่กำหนดโดยการสร้างลำดับแฟกทอเรียลทีละขั้นจนเกินช่วงที่กำหนด