#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAXM = 100010;
long long dp[12][70][2][2][2][2][2][2][2][2][2][2][2];
long long a[70];
bool judge(long long c[]) {
  for (int i = 0; i < 10; i++) {
    if (c[i] == 1) return false;
  }
  return true;
}
long long dfs(long long b, int cnt, int qd, int s, int fp, long long c[]) {
  if (!cnt) return s == 1;
  if (!fp && qd == 0 &&
      dp[b][cnt][c[0]][c[1]][c[2]][c[3]][c[4]][c[5]][c[6]][c[7]][c[8]][c[9]]
        [s] != -1)
    return dp[b][cnt][c[0]][c[1]][c[2]][c[3]][c[4]][c[5]][c[6]][c[7]][c[8]]
             [c[9]][s];
  long long n;
  if (fp)
    n = a[cnt];
  else
    n = b - 1;
  long long res = 0;
  for (int i = 0; i <= n; i++) {
    if (i == 0 && qd == 1)
      res += dfs(b, cnt - 1, 1, s, fp && i == n, c);
    else {
      c[i] = c[i] ^ 1;
      int tmp;
      if (judge(c))
        tmp = 1;
      else
        tmp = 0;
      res += dfs(b, cnt - 1, 0, tmp, fp && i == n, c);
      c[i] = c[i] ^ 1;
    }
  }
  if (!fp && qd == 0)
    dp[b][cnt][c[0]][c[1]][c[2]][c[3]][c[4]][c[5]][c[6]][c[7]][c[8]][c[9]][s] =
        res;
  return res;
}
long long sum(long long x, long long y) {
  int cnt = 0;
  long long c[12];
  memset(c, 0, sizeof(c));
  while (x) {
    a[++cnt] = x % y;
    x = x / y;
  }
  return dfs(y, cnt, 1, 0, 1, c);
}
int main() {
  int q;
  scanf("%d", &q);
  long long b, l, r;
  memset(dp, -1, sizeof(dp));
  while (q--) {
    scanf("%lld%lld%lld", &b, &l, &r);
    long long ans = sum(r, b) - sum(l - 1, b);
    printf("%lld\n", ans);
  }
  return 0;
}
