Cho khoảng [start, end], đếm số lượng số nguyên n sao cho n! nằm trong khoảng đó.
Ví dụ
Input - start = 5, end = 600 Output - 3
Giải thích - 3! = 6, 4! = 24, 5! = 120 (6! = 720 > 600). Có 3 giá trị: 3, 4, 5.
Input - start = 1, end = 100 Output - 5
Giải thích - 0! = 1, 1! = 1, 2! = 2, 3! = 6, 4! = 24 (5! = 120 > 100). Có 5 giá trị n.
Phương pháp tiếp cận
- Tìm giai thừa đầu tiên ≥ start
- Đếm các giai thừa tiếp theo ≤ end
- Tăng dần i và nhân dồn fact = fact * i
Ví dụ code C++
#include <iostream>
using namespace std;
int factorials(int start, int end) {
int fact = 1, i = 1;
while (fact < start) {
fact *= i;
i++;
}
int r = 0;
while (fact <= end) {
r++;
fact *= i;
i++;
}
return r;
}
int main() {
int start = 5, end = 600;
cout << "Count of factorial numbers are " << factorials(start, end);
return 0;
}
Kết quả
Count of factorial numbers are 3