Description
Roman is a young mathematician, very famous in Uzhland. Unfortunately, Sereja doesn’t think so. To make Sereja change his mind, Roman is ready to solve any mathematical problem. After some thought, Sereja asked Roma to find, how many numbers are close to number n, modulo m.
Number x is considered close to number n modulo m, if:
it can be obtained by rearranging the digits of number n,
it doesn’t have any leading zeroes,
the remainder after dividing number x by m equals 0.
Roman is a good mathematician, but the number of such numbers is too huge for him. So he asks you to help him.
Input
The first line contains two integers: n (1 ≤ n < 1e18) and m (1 ≤ m ≤ 100).
Output
In a single line print a single integer — the number of numbers close to number n modulo m.
Examples
Input
104 2
Output
3
Input
223 4
Output
1
Input
7067678 8
Output
47
Solution
因为n 最大为18位,且 m <= 100, 所以可以采用状压DP来求解
定义
d
p
[
s
]
[
k
]
dp[s][k]
dp[s][k] 为 各位数选用情况为
s
s
s , 余数为
k
k
k 时的方案数
转移方程:
dp[i][(k*10 + dig[j]) % m] += dp[i^(1<<j)][k];
注意因为同一种数字可能不止一个,所以答案可能会重复计算
一种方法是最后依次除以各数字数的阶乘,另一种是在dp时判断一下是否是用过的数字
Code
ll n,m;
ll dp[1<<18][107],a[20];
int dig[20],len,num[10];
int main(){
scanf("%lld%lld",&n,&m);
while(n){
dig[len++] = n % 10;
num[n % 10]++;
n /= 10;
}
for(int i = 0;i < len;++i)
if(dig[i]) dp[1<<i][dig[i]%m] = 1;
bool vis[10];clr(vis,false);
for(int i = 0;i < (1 << len);++i){
clr(vis,false);
for(int j = 0;j < len;++j){
if(i & (1<<j) && !vis[dig[j]]){
vis[dig[j]] = true;
for(int k = 0;k < m;++k)
dp[i][(k*10 + dig[j]) % m] += dp[i^(1<<j)][k];
}
}
}
printf("%lld\n", dp[(1 << len)-1][0]);
return 0;
}