給定素數 m 和整數 n (0 ≤ n ≤ 10000),求 n! 的質因數分解中素數 m 出現的次數。這是數論中的經典問題,直接應用Legendre 公式。
n! 中素數 p 的指數為:
eₚ(n!) = ⌊n/p⌋ + ⌊n/p²⌋ + ⌊n/p³⌋ + ... (直到 pᵏ > n)
n=100, m=5:
⌊100/5⌋ + ⌊100/25⌋ + ⌊100/125⌋ = 20 + 4 + 0 = 24
n=16, m=2:
⌊16/2⌋ + ⌊16/4⌋ + ⌊16/8⌋ + ⌊16/16⌋ = 8 + 4 + 2 + 1 = 15
#include <cstdio>
int count_factor_in_factorial(int n, int p) {
int count = 0;
for (long long pk = p; pk <= n; pk *= p) {
count += n / pk;
if (pk > n / p) break; // 防止 pk *= p 溢出
}
return count;
}
int main() {
int T; scanf("%d", &T);
while (T--) {
int n, m; scanf("%d %d", &n, &m);
printf("%d\n", count_factor_in_factorial(n, m));
}
return 0;
}
Legendre 公式是處理階乘質因數問題的核心工具,掌握它能輕鬆解決大量組合數論問題。