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

Example

Input
1
1 9
Output
9
Input
1
12 15
Output
2
思路:数位DP。
被每一位整除则用二进制记录已经包括的数字的个数,以及对2520取模后的状态。
由于对5整除当且仅当最后一个数为0或5,对2整除当且仅当最后一个数为偶数,且1~9的最小公倍数为2520,不包括2,5后的最小公倍数为252。
所以除最后一层对2520取模,其余时候都对252取模即可。
由于整除的状态有限,最多只有48个,于是我们预处理出这48个数,并来一个映射就好(不然会TLE)。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int t,cnt;
long long l,r;
int num[20],a[2521];
long long dp[20][260][50];
int gcd(int x,int y){
    return x==0?y:gcd(y%x,x);
}
long long dfs(int pos,int x,int y,bool limite){
    if(pos==-1)    return x%y==0;
    if(dp[pos][x][a[y]]!=-1&&!limite)    return dp[pos][x][a[y]];
    int up=limite?num[pos]:9;
    long long tmp=0;
    for(int i=0;i<=up;i++)
        tmp+=dfs(pos-1,pos?(x*10+i)%252:(x*10+i),i?y*i/gcd(y,i):y,limite&&i==num[pos]);
    if(!limite)    dp[pos][x][a[y]]=tmp;
    return tmp;
}
long long slove(long long now){
    int pos=0;
    while(now){
        num[pos++]=now%10;
        now/=10;
    }
    return dfs(pos-1,0,1,1);
}
int main(){
    scanf("%d",&t);
    for(int i=1;i<=2520;i++)
        if(2520%i==0)
            a[i]=cnt++;
    memset(dp,-1,sizeof(dp));
    while(t--){
        scanf("%I64d%I64d",&l,&r);
        cout<<slove(r)-slove(l-1)<<endl;
    }
} 

 

 

 

posted @ 2017-10-09 17:12  一蓑烟雨任生平  阅读(221)  评论(0编辑  收藏  举报