a positive integer number is beautiful if and only if it is divisible by each of its nonzero digits.
Find the quantities of beautiful numbers in given intervals (from li to ri, inclusively).
(1<=l<=r<=9e18)
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long LL;
const int MAXLEN = 20;
const int mod = 2520;
int digit[MAXLEN], t, has[mod+10];
LL ,a, b,dp[MAXLEN][mod][50]; // 数位长度,mod, lcm
// lcm虽然是[ 1, 2520 ] , 但是实际上 2520 = 2^3*3^2*5*7, 会出现的lcm只有48种。
LL gcd(LL a, LL b){
if(b==0)return a;
return gcd(b, a%b);
}
LL Lcm(LL a, LL b){
return a/gcd(a, b)*b;
}
LL DFS(int pos, int premod, int prelcm, bool limit) {
if(pos < 0) {
if(premod%prelcm==0)return 1LL;
return 0;
}
if(!limit && dp[pos][premod][has[prelcm]]!=-1)
return dp[pos][premod][has[prelcm]];
int ed = limit ? digit[pos] : 9;
LL ret = 0;
for(int i=0; i<=ed; ++i) {
int p = (premod*10+i)%2520;
if(i){
ret += DFS(pos-1, p, Lcm(i, prelcm), limit && i==ed);
}
else
ret += DFS(pos-1, p, prelcm, limit && i==ed);
}
if(!limit) dp[pos][premod][has[prelcm]] = ret;
return ret;
}
LL Calc(LL n) {
int len = 0;
while(n) {
digit[len++] = n%10;
n /= 10;
}
return DFS(len-1, 0, 1, true);
}
void init(){
int num = 1;
for(int i = 1; i<=mod; ++i){
if(mod%i==0)has[i] = num++;
}
memset(dp, -1, sizeof dp); //dp只需要在开始阶段初始化一次即可
}
int main() {
init();
scanf("%d", &t);
while(t--) {
scanf("%lld%lld", &a, &b);
printf("%lld\n", Calc(b)-Calc(a-1));
}
return 0;
}