Beautiful numbers

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 test(s)
Input
1
1 9
Output
9
Input
1
12 15
Output
2



问在区间【l,r】中有多少数能够整除他自身各位数——也就等价于问在区间【l,r】中有多少数能够整除他自身各位数的最小公倍数
嗯,又比上一个题更难一点了,没看题解前不会,果然我数位dp的理解还不到位啊……

数位DP时我们只需保存前面那些位的最小公倍数就可进行状态转移,到边界时就把所有位的lcm求出了
为了判断这个数能否被它的所有数位整除,我们还需要这个数的值,显然要记录值是不可能的,由于1到9 的最小公倍数是2520,我们只需记录它对2520的模即可,
所以呢dfs(pos,mod,lcm,f),pos为当前位,mod为前面那些位对2520的模,lcm为前面那些数位的最小公倍数,f标记前面那些位是否达到上限,这样一来dp数组就要开到19*2520*2520,明显超内存了,考虑到最小公倍数是离散的,1-2520中可能是最小公倍数的其实只有48个,经过离散化处理后,dp数组的最后一维可以降到48,这样就不会超了。


#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
typedef long long LL;
int num[80];
int cnt;
int bit[40];
LL f[40][80][2600];

int gcd(int a, int b)
{
	return b ? gcd(b, a % b) : a;
}  

LL dp(int pos, int lcm, int mod, bool flag)
{
	if (pos == 0) return mod % lcm == 0;
	if (flag && f[pos][num[lcm]][mod] != -1) return  f[pos][num[lcm]][mod];
	LL ans = 0;
	int x = flag ? 9 : bit[pos];
	for (int i = 0; i <= x; i++)
	{
		int tlcm = (i==0) ? lcm : lcm * i / gcd(lcm , i);
		int tmod = (mod * 10 + i) % 2520;
		ans += dp (pos - 1, tlcm, tmod, flag || i < x);  
	 
	}
	if (flag) f[pos][num[lcm]][mod] = ans;
	return ans; 
}

LL calc (LL x)
{
	int len = 0;
	while (x)
	{
		bit[++len] = x % 10;
		x /= 10; 
	}
	return dp(len, 1, 0, 0);
}
int main()
{
	int t;
	cnt = 0;
	for(int i = 1; i <= 2520; i++) if (2520 % i == 0) num[i] = cnt++;  
    memset(f, -1, sizeof(f));  
	scanf("%d", &t);
	while (t--)
	{
		LL l, r;
		scanf("%I64d%I64d", &l, &r);
		printf("%I64d\n", calc(r) - calc(l - 1));
	}
	return 0;
}