E-Beautiful Numbers (对每一位求模)

来源:互联网 发布:tm商标域名 编辑:程序博客网 时间:2024/05/18 03:30

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).

Example
Input
11 9
Output
9
Input
112 15
Output
2

      给l,r,求中间有多少个数满足对每一位都是整除的个数。

     看了半天,写了一半发现是不会的。开始的想法:数位dp是肯定不用说,dfs先对每一位求余,一直保留下来,中间能够满足每次都为0的一直继续,到最后pos=-1时判断mod是否为0,后来发现中间的求模并不对,只是用的前面部分,不是整个数。后来看人家的,确实有难度,涉及到一点数学问题,自己压根没有往这方面想了,最重要的一句话:对每一位整除《=》能整除每一位的最小公倍数。然后后面还是按位下来,1-9的最小公倍数2520的问题,开数组dp【30】【2520】【2520】太大,把最后面的离散化到数组lcm【】里,一共48个,先给预处理出来。自己做的时候错了好几次,没找到地方,所有int换成了LL过了,应该是哪里的数存不了了没找到。

        这里带一个博客链接,比较详细:点击打开链接

代码如下:

#include<iostream>#include<cstring>using namespace std;typedef long long LL;const LL MOD = 2520;LL bit[30];LL dp[30][MOD+10][50];LL lcm[MOD+10];//对应公倍数  离散LL gcd(LL a, LL b){if (b == 0)return a;return gcd(b, a%b);}LL LCM(LL a, LL b){return a * b / gcd(a, b);}void init(){memset(lcm, 0, sizeof(lcm));LL k = 0;for (LL i = 1; i <= MOD; i++){if (MOD%i == 0)lcm[i] = k++;}}//        数位     余数   公倍数     上界LL dfs(LL pos, LL mod, LL sta, bool limit){if (pos <= -1){if (mod%sta == 0)return 1;return 0;}if (!limit && dp[pos][mod][lcm[sta]] != -1){return dp[pos][mod][lcm[sta]];}LL up = limit ? bit[pos] : 9;LL temp = 0;for (LL i = 0; i <= up; i++){LL mod2 = (mod * 10 + i) % MOD;LL sta2 = sta;if (i)sta2 = LCM(sta, i);temp += dfs(pos - 1, mod2, sta2, limit && i == up);}if (!limit)dp[pos][mod][lcm[sta]] = temp;return temp;}LL solve(LL x){LL pos = 0;while(x){bit[pos++] = x % 10;x /= 10;}return dfs(pos - 1, 0, 1, 1);}int main(){LL t;LL le, ri;cin >> t;init();memset(dp, -1, sizeof(dp));while (t--){cin >> le >> ri;cout << solve(ri) - solve(le - 1) << endl;}return 0;}