codeforces 55D beautiful number数位dp加离散化

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
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define ull unsigned long long
using namespace std;
ull dp[30][50][2600];
int Hash[2600];
int bit[30];
int t;
int gcd(int a,int b)
{
    return b==0?a:gcd(b,a%b);
}
int lcm(int a,int b)
{
    return a/gcd(a,b)*b;
}
ull dfs(int pos,int prelcm,int prenum,int limit)
{
    if(pos==-1)
        return prenum%prelcm==0;
    if(!limit&&dp[pos][Hash[prelcm]][prenum]!=-1)
        return dp[pos][Hash[prelcm]][prenum];
    int up=limit?bit[pos]:9;
    ull ans=0;

    for(int i=0;i<=up;i++)
    {
        int prelcm1=prelcm;
        if(i)
        prelcm1=lcm(prelcm,i);
        int prenum1=(prenum*10+i)%2520;
        ans+=dfs(pos-1,prelcm1,prenum1,limit&&(i==up));
    }
    if(!limit)
    dp[pos][Hash[prelcm]][prenum]=ans;
    return ans;
}
ull solve(ull x)
{
    int pos=0;
    while(x)
    {
        bit[pos++]=x%10;
        x/=10;
    }
    return dfs(pos-1,1,0,1);

}
int main()
{
    scanf("%d",&t);

    int cnt=0;
    for(int i=1;i<=2520;i++)
    if(2520%i==0)
        Hash[i]=++cnt;
        memset(dp,-1,sizeof(dp));
    while(t--)
    {
        ull l,r;

        scanf("%llu%llu",&l,&r);
        printf("%llu\n",solve(r)-solve(l-1));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/sdauguanweihong/article/details/89194537