#include <bits/stdc++.h>
using namespace std;
long long k, l, r, p, t, ans = 0, sp;
long long Ksm(long long x, long long base, long long Mod) {
  if (x == 0) return 0;
  if (base == 0)
    return 1;
  else if (base == 1)
    return x % Mod;
  else {
    long long tmp = Ksm(x, base >> 1, Mod);
    if (base & 1)
      return (((tmp * tmp) % Mod) * x) % Mod;
    else
      return (tmp * tmp) % Mod;
  }
}
int main() {
  scanf("%I64d", &t);
  for (long long i = 1; i <= t; i++) {
    scanf("%I64d %I64d %I64d %I64d", &k, &l, &r, &p);
    if (p == 2 && (k & 1))
      printf("0\n");
    else if (p == 2 && !(k & 1))
      printf("1\n");
    else if (k == 1)
      printf("2\n");
    else {
      if (k & 1)
        sp = Ksm(2, p - 2, p), sp = Ksm(sp, r - l, p);
      else
        sp = 1;
      k %= p;
      long long tmp = Ksm(2, r + 1, p - 1);
      tmp = Ksm(k, tmp, p);
      long long get = Ksm(2, l, p - 1);
      get = Ksm(k, get, p);
      if (get != 1)
        ans = (sp * (tmp - 1) % p) * Ksm(get - 1, p - 2, p) % p;
      else
        ans = sp * Ksm(2, r - l + 1, p) % p;
      printf("%I64d\n", (ans + p) % p);
    }
  }
  return 0;
}
