A - Beautiful numbers CodeForces - 55D

本文介绍了一种算法,用于计算在给定范围内满足特定条件的正整数数量,这些整数被称为“美丽数”。美丽数的定义是:一个正整数如果能被其所有非零数字整除,则该数为美丽数。文章提供了详细的算法实现,包括使用动态规划和数学运算来高效地解决此问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MOD=2520;//1~9公共的最小公倍数
ll gcd(ll a,ll b){return b==0?a:gcd(b,a%b);}
ll lcm(ll a,ll b){return a*b/gcd(a,b);}
ll dp[30][MOD][50];
ll a[30],Hash[MOD];
ll DFS(int pos,int presum,int prelcm,int limit)
{
    if(pos==0)
        return presum%prelcm==0;//返回逻辑值
    if(!limit&&dp[pos][presum][Hash[prelcm]]!=-1)
        return dp[pos][presum][Hash[prelcm]];
    int up=limit?a[pos]:9;
    ll res=0;
    for(int i=0;i<=up;i++){
        int nowsum=(presum*10+i)%MOD;//可以对MOD任意取模而不影响结果
        int nowlcm=prelcm;
        if(i!=0)
            nowlcm=lcm(prelcm,i);
        res+=DFS(pos-1,nowsum,nowlcm,limit&&i==up);
    }
    if(limit)
        return res;
    return dp[pos][presum][Hash[prelcm]]=res;
}
ll solve(ll n)
{
    int top=0;
    while(n){
        a[++top]=n%10;
        n/=10;
    }
    return DFS(top,0,1,1);
}
void Init()
{
    int cnt=0;
    for(int i=1;i<=2520;i++){//Hash一下
        if(MOD%i==0)
            Hash[i]=cnt++;
    }
}
int main()
{
    ios::sync_with_stdio(0);
    Init();
    int T;
    memset(dp,-1,sizeof(dp));
    cin>>T;
    while(T--){
        ll l,r;
        cin>>l>>r;
        cout<<solve(r)-solve(l-1)<<endl;
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值