找[l,r]区间中,能被自己各个非零数位整除的数的个数。

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

Examples

Input

1
1 9

Output

9

Input

1
12 15

Output

2
一看就是满足区间减法。现在就讨论怎么求就行了。
首先lcm(1..9)=2520, int MOD=2520;保存每一个数是不现实的,所以我们就.保存x%MOD就行了。
preSum表示已经讨论的前面的几个数位的值(前串),preLcm表示前穿的Lcm。
这里注意到1...9的各种lcm可以离散化处理,只有48个,这样可以大大减少数组的空间。
我们再用flag来表示当前位的数字大小是否超过x对应位的大小
例:x=15666;当我们讨论到千位是1,2,3,4时,后面三位是随便选的,讨论千位是5是,百位就不能随便选了,要<=6,此时在千位我们就达到了边界。

代码:

#include<iostream>
#include<cstring>
using namespace std;
const int MAXN=25;
const int MOD=2520;
long long dp[MAXN][MOD][48];
int index[MOD+10],bit[MAXN];
long long int gcd (long long int a,long long int b) {return (b==0)?a:gcd(b,a%b);}
long long int lcm (long long int a,long long int b){return a/gcd(a,b)*b;}
void init()
{
    int num=0;
    for (int i=1;i<=MOD;++i)
    if (MOD%i==0)
    index[i]=num++;//   把2520的所有因子进行编号,第一个因子编号1..........
}
long long dfs (int pos,int preSum,int preLcm,bool flag)
{
    if (pos==-1)
    return preSum%preLcm==0;
    if (!flag && dp[pos][preSum][index[preLcm]]!=-1)
    return dp[pos][preSum][index[preLcm]];
    long long ans=0;
    int endd=flag?bit[pos]:9;
    for (int i=0;i<=endd;i++)
    {
        int nowSum=(preSum*10+i)%MOD;
        int nowLcm=preLcm;
        if (i)
        nowLcm=lcm(nowLcm,i);
        ans+=dfs(pos-1,nowSum,nowLcm,flag&&i==endd);
    }
    if (!flag)
    dp[pos][preSum][index[preLcm]]=ans;
    return ans;
}
long long calc (long long x)
{
    memset(bit,0,sizeof bit);
    int pos=0;
    while (x)
    {
        bit[pos++]=x%10;
        x/=10;
    }
    return dfs(pos-1,0,1,1);
}
int main()
{
    int t;
    long long int l,r;
    memset(dp,-1,sizeof dp);
   cin>>t;
    init();
    while (t--)
    {
        cin>>l>>r;
       cout<<calc(r)-calc(l-1)<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40859951/article/details/82527240
今日推荐