10
4 108 114
5 30 155
8 193 197
9 71 169
2 163 166
8 120 144
8 22 151
4 21 166
2 46 127
8 38 51
 20
9 142 172
7 132 256
8 245 315
9 496 496
3 345 362
8 13 162
5 342 470
9 16 488
9 467 482
4 471 478
10 92 224
6 228 261
9 54 167
2 402 409
5 9 10
7 225 360
3 438 483
6 252 342
3 491 493
6 296 367
 1
8 1234567890123 123456789012345

0
3
0
1
3
0
5
16
9
1
 0
0
0
0
4
6
13
7
0
0
1
2
3
0
0
2
12
9
1
4
 774752389568

#include <bits/stdc++.h>
using namespace std;
map<pair<long long, long long>, long long> ans;
string str;
long long Size, base;
long long dpc, solc, dp[100][2048][2][2], sol[100][2048][2];
long long bolve(int pos, int mask, int is_zero) {
  if (pos == Size) return mask == 0;
  if (sol[pos][mask][is_zero] == solc) return sol[pos][mask][is_zero];
  sol[pos][mask][is_zero] == solc;
  long long ret = 0;
  for (int i = 0; i < base; i++) {
    if (is_zero && i == 0)
      ret += bolve(pos + 1, mask, true);
    else
      ret += bolve(pos + 1, mask ^ (1 << i), false);
  }
  return sol[pos][mask][is_zero] = ret;
}
long long solve(int pos, int mask, int is_less, int is_zero) {
  if (pos == Size) return mask == 0;
  if (is_less) {
    return bolve(pos, mask, is_zero);
  }
  if (dp[pos][mask][is_less][is_zero] == dpc) {
    return dp[pos][mask][is_less][is_zero];
  }
  dp[pos][mask][is_less][is_zero] == dpc;
  int b = str[pos] - '0';
  long long ret = 0;
  for (int i = 0; i < b; i++) {
    if (is_zero && i == 0) {
      ret += solve(pos + 1, mask, true, true);
    } else {
      ret += solve(pos + 1, mask ^ (1 << i), true, false);
    }
  }
  if (is_zero && b == 0) {
    ret += solve(pos + 1, mask, false, true);
  } else {
    ret += solve(pos + 1, mask ^ (1 << b), false, false);
  }
  return dp[pos][mask][is_less][is_zero] = ret;
}
string convert(long long n) {
  string fuck;
  for (int i = 0; i < Size; i++) {
    fuck += '0' + n % base;
    n /= base;
  }
  reverse(fuck.begin(), fuck.end());
  return fuck;
}
long long l[10000000], r[10000000], b[10000000], q;
vector<long long> vec[11];
int main() {
  cin >> q;
  for (int i = 0; i < q; i++) cin >> b[i] >> l[i] >> r[i];
  for (int i = 0; i < q; i++) {
    vec[b[i]].push_back(l[i] - 1);
    vec[b[i]].push_back(r[i]);
  }
  for (int i = 2; i <= 10; i++) {
    solc++;
    base = i;
    long long x = 5e18;
    int fuck = 0;
    while (x) {
      x = x / base;
      fuck++;
    }
    Size = fuck;
    for (int j = 0; j < vec[i].size(); j++) {
      str = convert(vec[i][j]);
      dpc += 10;
      ans[make_pair(i, vec[i][j])] = solve(0, 0, 0, 1);
    }
  }
  for (int i = 0; i < q; i++) {
    long long part = ans[make_pair(b[i], l[i] - 1)];
    long long fin = ans[make_pair(b[i], r[i])] - part;
    cout << fin << endl;
  }
}
