#include <bits/stdc++.h>
using namespace std;
void read(int& x) {
  bool fu = 0;
  char c;
  for (c = getchar(); c <= 32; c = getchar())
    ;
  if (c == '-') fu = 1, c = getchar();
  for (x = 0; c > 32; c = getchar()) x = x * 10 + c - '0';
  if (fu) x = -x;
};
void read(long long& x) {
  bool fu = 0;
  char c;
  for (c = getchar(); c <= 32; c = getchar())
    ;
  if (c == '-') fu = 1, c = getchar();
  for (x = 0; c > 32; c = getchar()) x = x * 10 + c - '0';
  if (fu) x = -x;
};
char getc() {
  char c;
  for (c = getchar(); c <= 32; c = getchar())
    ;
  return c;
}
long long T, k, l, r, p, t1, t2, tt, ans;
long long pow(long long a, long long b, long long c) {
  long long ans = 1;
  a %= c;
  for (; b; b >>= 1, a = a * a % c)
    if (b & 1) ans = ans * a % c;
  return ans;
}
int main() {
  for (read(T); T; T--) {
    read(k);
    read(l);
    read(r);
    read(p);
    if (p == 2) {
      if (k & 1)
        printf("0\n");
      else
        printf("1\n");
    } else if (k == 1) {
      printf("%I64d\n", 2 % p);
    } else {
      if (pow(k, pow(2LL, l, p - 1) + (p - 1), p) == 1) {
        ans = pow(2, r - l + 1, p);
      } else {
        t1 = (pow(k, pow(2LL, r + 1, p - 1) + (p - 1), p) + (p - 1)) % p;
        t2 = (pow(k, pow(2LL, l, p - 1) + (p - 1), p) + (p - 1)) % p;
        ans = (t1 * pow(t2, p - 2, p) % p + p) % p;
      }
      if (k & 1) ans = (ans * pow(pow(2LL, r - l, p), p - 2, p) % p + p) % p;
      printf("%I64d\n", ans);
    }
  }
  scanf("\n");
  return 0;
}
