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;
const int N = int(1e5) + 5;
const int inf = (int)1e9 + 7;
const long long linf = (long long)1e18 + 7;
int q;
long long f[19];
long long dp[65][(1 << 11)][11];
string to(long long x, int base) {
  string ans;
  while (x > 0) {
    ans += char(x % base + '0');
    x /= base;
  }
  reverse(ans.begin(), ans.end());
  return ans;
}
void precalc() {
  for (int base = 2; base <= 10; ++base) {
    dp[0][0][base] = 1;
    for (int l = 0; l < 64; ++l) {
      for (int j = 0; j < (1 << base); ++j) {
        for (int nxt = !l ? 1 : 0; nxt < base; ++nxt) {
          dp[l + 1][j ^ (1 << nxt)][base] += dp[l][j][base];
        }
      }
    }
  }
}
int good(string x) {
  vector<int> cnt(10);
  for (char j : x) {
    cnt[j - '0']++;
  }
  for (int i = 0; i < 10; ++i) {
    if (cnt[i] & 1) {
      return 0;
    }
  }
  return 1;
}
long long solve(string &r, int base) {
  if (r.empty()) {
    return 0;
  }
  long long tot = 0;
  for (int l = 1; l < (int)r.size(); ++l) {
    tot += dp[l][0][base];
  }
  int my = 0;
  for (int pos = 0; pos < (int)r.size(); ++pos) {
    for (int j = pos == 0 ? 1 : 0; j < r[pos] - '0'; ++j) {
      int nm = my ^ (1 << j);
      int to = __builtin_popcount(nm);
      int rem = (int)r.size() - pos - 1;
      if (to > rem) {
        continue;
      }
      tot += f[to] * dp[rem - to][0][base];
    }
    my ^= (1 << (r[pos] - '0'));
  }
  return tot + good(r);
}
int main() {
  ios_base ::sync_with_stdio(false);
  cin.tie(nullptr);
  cin >> q;
  f[0] = 1;
  for (int i = 1; i <= 18; ++i) {
    f[i] = f[i - 1] * 1ll * i;
  }
  precalc();
  for (int i = 1; i <= q; ++i) {
    long long b, li, ri;
    cin >> b >> li >> ri;
    if (li == (long long)1e18 && ri == (long long)1e18) {
      cout << good(to(li, b)) << "\n";
      continue;
    }
    int kek = 0;
    if (ri == (long long)1e18) {
      kek += good(to(ri, b));
      --ri;
    }
    string l = to(li - 1, b);
    string r = to(ri, b);
    cout << solve(r, b) - solve(l, b) + kek << "\n";
  }
  return 0;
}
