Description
Volodya is an odd boy and his taste is strange as well. It seems to him that a positive integer number is beautiful if and only if it is divisible by each of its nonzero digits. We will not argue with this and just count the quantity of beautiful numbers in given ranges.
Input
The first line of the input contains the number of cases t (1 ≤ t ≤ 10). Each of the next t lines contains two natural numbers li and ri (1 ≤ li ≤ ri ≤ 9 ·1018).
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d).
Output
Output should contain t numbers — answers to the queries, one number per line — quantities of beautiful numbers in given intervals (from li to ri, inclusively).
Sample Input
1
1 9
9
1
12 15
2
题意是给出一个范围,求这个范围中beautiful number的数量,beautiful number就是指一个数能被自身各个位置上的数整除。
显然的,beautiful number自身一定要被各位上的数的最小公倍数整除。0~9的最小公倍数种类实际上是很少的,也是很小的(2520)。因此可以用dp[20][50][2521]来保存状态。dp[pos][id][lcm], id指的是某种最小公倍数。因为最小公倍数最大只有2520,所以可以num %= 2520,答案不变。接下来就可以上数位dp模板了
#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> using namespace std; #define ll long long int dig[50]; ll dp[20][50][2521]; int id[2521]; ll getlcm(ll a, ll b) { return a / __gcd(a, b) * b; } ll dfs(int pos, ll lcm, ll sum, int lim) { if(pos == -1) return sum % lcm == 0; if(dp[pos][id[lcm]][sum] != -1 && !lim) return dp[pos][id[lcm]][sum]; int End = lim ? dig[pos] : 9; ll ret = 0; for(int i = 0; i <= End; i++) { ll nlcm = lcm; if(i) nlcm = getlcm(nlcm, i); ll nsum = sum * 10 + i; if(pos) nsum %= 2520; ret += dfs(pos - 1, nlcm, nsum, i == End && lim); } if(!lim) dp[pos][id[lcm]][sum] = ret; return ret; } ll func(ll a) { int n = 0; while(a) { dig[n++] = a % 10; a /= 10; } return dfs(n - 1, 1, 0, 1); } void init() { int tmp = 0; for(int i = 1; i <= 2520; i++) if(2520 % i == 0) id[i] = tmp++; memset(dp, -1, sizeof(dp)); } int main() { int t; init(); scanf("%d", &t); while(t--) { ll a, b; scanf("%I64d %I64d", &a, &b); printf("%I64d\n", func(b) - func(a - 1)); } }