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;
long long dp[11][20][2050];
int n, b;
int v[20];
long long solve(int pos, bool lss, int mask) {
  if (pos > n) {
    return mask == 0;
  }
  if (lss) {
    int len = n - pos + 1;
    return dp[b][len][mask ^ ((1 << b) - 1)] -
           dp[b][len - 1][mask ^ ((1 << b) - 1) ^ 1];
  }
  long long ret = solve(pos + 1, false, mask ^ (1 << v[pos]));
  for (int cif = (pos == 1 ? 1 : 0); cif < v[pos]; cif++) {
    ret += solve(pos + 1, true, mask ^ (1 << v[pos]));
  }
  return ret;
}
int main() {
  for (int base = 2; base <= 10; base++) {
    for (int cif = 0; cif < base; cif++) {
      dp[base][1][1 << cif] = 1;
    }
    for (int len = 2; len <= 19; len++) {
      for (int mask = 0; mask <= (1 << base) - 1; mask++) {
        for (int cif = 0; cif < base; cif++) {
          dp[base][len][mask ^ (1 << cif)] += dp[base][len - 1][mask];
        }
      }
    }
  }
  int q;
  cin >> q;
  while (q--) {
    int b;
    long long l, r;
    long long ansl, ansr;
    cin >> b;
    cin >> l;
    l--;
    n = 0;
    while (l) {
      v[++n] = l % b;
      l /= b;
    }
    reverse(v + 1, v + n + 1);
    ansl = (n == 0 ? 0 : solve(1, false, 0));
    for (int i = 1; i < n; i++) {
      ansl += dp[b][i][0];
      if (i > 1) {
        ansl -= dp[b][i - 1][1];
      }
    }
    cin >> r;
    n = 0;
    while (r) {
      v[++n] = r % b;
      r /= b;
    }
    reverse(v + 1, v + n + 1);
    ansr = solve(1, false, 0);
    for (int i = 1; i < n; i++) {
      ansr += dp[b][i][0];
      if (i > 1) {
        ansr -= dp[b][i - 1][1];
      }
    }
    cout << ansr - ansl << '\n';
  }
  return 0;
}
