#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
template <class T>
void Read(T &x) {
  x = 0;
  char c = getchar();
  bool flag = 0;
  while (c < '0' || '9' < c) {
    if (c == '-') flag = 1;
    c = getchar();
  }
  while ('0' <= c && c <= '9') {
    x = x * 10 + c - '0';
    c = getchar();
  }
  if (flag) x = -x;
}
inline int ksm(int a, long long int p, int mod) {
  a %= mod;
  int ret = 1;
  while (p) {
    if (p & 1) ret = 1ll * ret * a % mod;
    p >>= 1;
    a = 1ll * a * a % mod;
  }
  return ret;
}
int k, p;
long long int l, r;
inline int F(long long int x) {
  return k % p == 0 ? p - 1 : (ksm(k, ksm(2, x, p - 1), p) - 1 + p) % p;
}
inline int inv(int v) { return ksm(v, p - 2, p); }
int main() {
  int T;
  Read(T);
  while (T--) {
    Read(k), Read(l), Read(r), Read(p);
    printf("%d\n", p == 2 ? (k & 1 ? 0 : 1)
                          : 1ll *
                                (F(l) ? 1ll * F(r + 1) * inv(F(l)) % p
                                      : ksm(2, r - l + 1, p)) *
                                (k & 1 ? inv(ksm(2, r - l, p)) : 1) % p);
  }
}
