#include #include #define rep2(i, k, n) for (i64 i = (i64)(k); i < (i64)(n); i++) #define rep(i, n) rep2(i, 0, n) #define all(x) begin(x), end(x) #ifdef ENV_LOCAL #define dump \ if (1) cerr #else #define dump \ if (0) cerr #endif using namespace std; using namespace std::string_literals; using i32 = int32_t; using i64 = int64_t; using f64 = double; using f80 = long double; using vi32 = vector; using vi64 = vector; // using namespace harudake; i64 f(i64 i, i64 c) { i64 ans = 0; while (i > 0) { if (i % 10 == c) ++ans; i /= 10; } return ans; } constexpr i64 mul = 100000; i64 solve_large(i64 r, i64 k, i64 c) { i64 ans = 0; for (i64 i = 0; i + mul < r; i += mul) { i64 v = f(i, c); i64 num = (i + mul - 1) / k - (i - 1) / k; ans += v * num; } i64 last = r / mul * mul; i64 lstart = (last + k - 1) / k * k; for (i64 i = lstart; i <= r; i += k) { ans += f(i / mul, c); } return ans; } i64 solve_small(i64 r, i64 k, i64 c) { i64 ans = 0; unordered_map m; vi64 seq; m[0] = 0; seq.push_back(0); i64 num = k % mul; i64 coeff = 1; while (num <= r) { if (m.count(num) > 0) { break; } m[num] = coeff; seq.push_back(f(num, c)); num += k; num %= mul; ++coeff; } i64 cycle = coeff - m[num]; i64 beg = m[num]; i64 d = r / k; if (d <= beg) { rep(i, d + 1) { ans += seq[i]; } } else { i64 c = (d - beg) / cycle; i64 r = (d - beg) % cycle; rep(i, beg) { ans += seq[i]; } rep2(i, beg, coeff) { ans += c * seq[i]; } rep2(i, beg, beg + r + 1) { ans += seq[i]; } } return ans; } i64 solve_naive_large(i64 r, i64 k, i64 c) { i64 ans = 0; for (i64 i = k; i <= r; i += k) { ans += f(i / mul, c); } return ans; } i64 solve(i64 r, i64 k, i64 c) { i64 s = solve_small(r, k, c); i64 l = solve_large(r, k, c); // i64 nl = solve_naive_large(r, k, c); // dump << s << " " << l << " " << nl << endl; return s + l; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); i64 t; cin >> t; rep(ccnt, t) { i64 l, r, k, c; cin >> l >> r >> k >> c; i64 ans = solve(r, k, c) - solve(l - 1, k, c); cout << ans << "\n"; } return 0; }