#include <bits/stdc++.h>
using namespace std;
const int oo = 1047483647, maxn = 310;
int wo, t, n, i, j, k, m, q, p;
long long l, r;
int get(int x, long long ci, int Mod) {
  if (ci == 0)
    return 1 % Mod;
  else if (ci == 1)
    return x % Mod;
  else {
    int tmp = get(x, ci / 2, Mod);
    tmp = (long long)tmp * tmp % Mod;
    if (ci & 1) tmp = (long long)tmp * x % Mod;
    return tmp;
  }
}
int ni(int x) { return get(x, p - 2, p); }
int main() {
  scanf("%d", &t);
  for (wo = 1; wo <= t; wo++) {
    scanf("%d%I64d%I64d%d", &k, &l, &r, &p);
    if (k == 1) {
      printf("%d\n", 2 % p);
      continue;
    }
    int c1 = get(2, r + 1, p - 1);
    int c2;
    c2 = get(2, l, p - 1);
    if (get(k, c2, p) - 1 == 0 && k % p) {
      int c3 = get(2, r - l + 1, p);
      if (!l) {
        c3 = get(2, r - l, p);
        c3 = (long long)c3 * (get(k, c2, p) + 1) % p;
      }
      if (k & 1) {
        r = r - l;
        int tm = get(2, r, p);
        tm = ni(tm);
        c3 = (long long)c3 * tm % p;
      }
      printf("%d\n", c3);
      continue;
    }
    int s1 = get(k, c1, p);
    s1 = (s1 - 1 + p) % p;
    int s2 = get(k, c2, p);
    s2 = (s2 - 1 + p) % p;
    s2 = ni(s2);
    if (l)
      s1 = (long long)s1 * s2 % p;
    else
      s1 = (long long)s1 * ni(k - 1) % p;
    if (k % p == 0) s1 = 1;
    if (k & 1) {
      r = r - l;
      int tm = get(2, r, p);
      tm = ni(tm);
      s1 = (long long)s1 * tm % p;
    }
    printf("%d\n", s1);
  }
  return 0;
}
