# P1591 階乘數碼 （高精階乘）

## 輸入輸出樣例

```2
5 2
7 0```

```1
2```

``````#include <iostream>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>

using namespace std;

typedef long long LL;

//手動memset整個數組爲-1
void bitset(char *s, int n)
{
for (int i = 0; i < n; ++i)
s[i] = -1;
}

//將-1作爲數組結束的標誌來複制數組
void arrcpy(char *s, char *s2)
{
for (int i = 0; s2[i] != -1; ++i)
s[i] = s2[i];
}

//以-1爲數組結束的標誌來計算數組內的有效長度
int len(char *s)
{
int res = 0;
while (s[res++] != -1)
;
return res - 1;
}

//輸出數組，用於debug
void show(char *s)
{
for (int i = 0; s[i] != -1; ++i)
cout << char(s[i] + '0');
cout << endl;
}

LL fa(int n, int a)
{

char f1[10000];
char f2[4];
char res[10000];

bitset(f1, 10000);
bitset(f2, 4);
bitset(res, 10000);

f1[0] = 1;//初始爲1
int l1;//l1 爲 f1的有效長度，l2爲f2的有效長度
for (int i = 1; i <= n; ++i)
{
bitset(f2, 4);
int tmp = i;
int l2 = 0;
while (tmp)//構造每次的乘數
{
f2[l2++] = tmp % 10;
tmp /= 10;
}
l1 = len(f1);//由於每輪都會將res拷貝到f1裏，所以需要統計一次長度
int m;
for (int j = 0; j < l1; ++j)
{
m = 0;
int k;
for (k = 0; k < l2; ++k)
{
m += f1[j] * f2[k];
if (res[j + k] > 0)
m += res[j + k];
res[j + k] = m % 10;
m /= 10;
}
if (m)
res[j + k] = (res[j + k] > 0 ? res[j + k] : 0) + m;
}
bitset(f1, 10000);
arrcpy(f1, res);
bitset(res, 10000);
//show(f1);
}

//統計a出現的次數
int c = 0;
for (int i = 0; f1[i] >= 0; ++i)
if (f1[i] == a)
++c;

return c;
}

int main()
{
//freopen("1.txt", "r", stdin);

int t;
cin >> t;
int n, a;
while (t--)
{
cin >> n >> a;
cout << fa(n, a) << endl;
}

return 0;
}``````