CodeForces - 55D Beautiful numbers

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值