1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
/*
Rozwiazanie na podstawie artykulu i kodu stad:
 https://www.geeksforgeeks.org/number-of-integers-in-a-range-l-r-which-are-divisible-by-exactly-k-of-its-digits/
*/

#include <bits/stdc++.h>
using namespace std;

typedef long long int LL;

const int LCM = 2520;
const int MAX_MASK = (1 << 9) + 1;
const int MAX_LEN = 19;

LL l, r;

LL states[MAX_LEN][2][LCM][MAX_MASK];

vector<int> digits;

LL dp(const int idx, const int canZero, const int tight, const int rem, const int mask)
{
    LL& res = states[idx][tight][rem][mask];

    if(res != -1)
    {
        return res;
    }

    res = 0;

    if(idx == digits.size())
    {
        int usedDigsCount = 0, divisibleByDigsCount = 0;

        for(int d = 1; d < 10; ++d)
        {
            if(mask & (1 << (d-1)))
            {
                ++usedDigsCount;
                if(rem % d == 0)
                {
                    ++divisibleByDigsCount;
                }
            }
        }

        if(usedDigsCount == divisibleByDigsCount && usedDigsCount > 0)
        {
            res = 1;
        }
    }
    else
    {
        for(int d = (canZero ? 0 : 1); d < 10; ++d)
        {
            if(tight && d > digits[idx])
            {
                continue;
            }

            const int newTight = ((tight == 1) ? (d == digits[idx]) : 0);
            const int newRem = (10*rem + d) % LCM;
            const int newCanZero = (canZero && (d == 0));

            int newMask = mask;
            if(d != 0)
            {
                newMask = (mask | (1 << (d-1)));
            }

            res += dp(idx+1, newCanZero, newTight, newRem, newMask);
        }
    }

    return res;
}

LL findCount(LL x)
{
    digits.clear();
    while(x > 0)
    {
        digits.push_back(x%10);
        x /= 10;
    }

    reverse(digits.begin(), digits.end());

    memset(states, -1, sizeof(states));
    return dp(0, 1, 1, 0, 0);
}

int main()
{
    ios_base::sync_with_stdio(0);

    cin >> l >> r;
    cout << findCount(r) - findCount(l-1) << endl;

    return 0;
}