Beautiful numbers (数位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

题意:给定a,b,求a,b之间所有能被自己每一个非零位整除的数的个数。

分析:也就是能被非零位的最小公倍数整除的数的个数

预处理出所有的最小公倍数,发现一共48个,最大是2520,那么就可以让2520作mod

(所有的最小公倍数都2520的因数,这样不影响结果)

然后就是简单的数位dp了

#include<bits/stdc++.h>
//#include<cstdio>
//#include<algorithm>
//#include<cstring>
//#include<map>
//#include<iostream>
#pragma GCC optimize(3)
#define max(a,b) a>b?a:b
using namespace std;
typedef long long ll;
const int mod=2520;
ll lcm(ll a,ll b){
	return a/__gcd(a,b)*b;
}
int cnt=0;//最大48 
int HASH[mod+100];
int num[50];
void init(){   //预处理所有最小公倍数
	for(int i=1;i<=mod;i++){
		if(mod%i==0){
			HASH[i]=++cnt;
			num[cnt]=i;
		} 
	}
}
ll dp[25][mod+5][50];
int a[25];
ll dfs(int pos,int sta,int index,bool limit){
	if(pos==0) return sta%num[index]==0;
	if(!limit&&dp[pos][sta][index]!=-1) return dp[pos][sta][index];
	int up=limit?a[pos]:9;
	ll ans=0;
	for(int i=0;i<=up;i++){
		int new_sta=(sta*10+i)%mod;
		int LCM=num[index];
		if(i) LCM=lcm(LCM,i);
		ans+=dfs(pos-1,new_sta,HASH[LCM],limit&&i==up);
	}
	if(!limit) dp[pos][sta][index]=ans;
	return ans;
} 
ll solve(ll x){
	int pos=0;
	while(x){
		a[++pos]=x%10;
		x/=10;
	}
	return dfs(pos,0,1,true);
}
int main(){
	ios::sync_with_stdio(false);
    cout.tie(NULL);
    init();
    int T;
    scanf("%d",&T);
    memset(dp,-1,sizeof(dp)); 
    while(T--){
    	ll a,b;
    	scanf("%I64d%I64d",&a,&b);
    	printf("%I64d\n",solve(b)-solve(a-1));
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值