洛谷-P1591 階乘數碼
阿新 • • 發佈:2020-08-07
洛谷-P1591 階乘數碼
題目描述
求 \(n!\) 中某個數碼出現的次數。
輸入格式
第一行為 \(t(t \leq 10)\),表示資料組數。接下來 \(t\) 行,每行一個正整數 \(n(n \leq 1000)\) 和數碼 \(a\)。
輸出格式
對於每組資料,輸出一個整數,表示 \(n!\) 中 \(a\) 出現的次數。
輸入輸出樣例
輸入 #1
2
5 2
7 0
輸出 #1
1
2
C++程式碼
#include <iostream> #include <cstring> using namespace std; int f[5001]; void mmultip(int a[], int c) { int jw = 0; for (int i=1; i<=5000; ++i) { a[i] = a[i] * c + jw; jw = a[i] /10; a[i] %= 10; } } int countA (int n, int a) { int i, count = 0; memset(f, 0, sizeof(f)); f[1] = 1; for (i=2; i<=n; ++i) mmultip(f, i); for (i=5000; f[i] == 0; --i); for (; i>=1; --i) if (f[i] == a) ++count; return count; } int main() { int t; cin >> t; int n[t], a[t], ans[t]; for (int i=0; i<t; ++i) cin >> n[i] >> a[i]; for (int i=0; i<t; ++i) ans[i] = countA(n[i], a[i]); for (int i=0; i<t; ++i) cout << ans[i] << endl; return 0; }