#include <bits/stdc++.h>
const int INF = 0x3f3f3f3f;
const long long int INFLL = 0x3f3f3f3f3f3f3f3fll;
long long int getint() {
  long long int ret = 0;
  bool f = 0;
  char c;
  while ((c = getchar()) < '0' || c > '9')
    if (c == '-') f ^= 1;
  while (c >= '0' && c <= '9') {
    ret = ret * 10 + c - '0';
    c = getchar();
  }
  return f ? -ret : ret;
}
using namespace std;
int k, p;
long long int l, r;
int mypow(int a, long long int b, int mod) {
  int ret = 1;
  for (; b; b >>= 1, a = (long long int)a * a % mod)
    if (b & 1) ret = (long long int)ret * a % mod;
  return ret;
}
int work() {
  k = getint();
  l = getint(), r = getint();
  p = getint();
  if (p == 2) return (k & 1) ? 0 : 1;
  if (k % p == 0) return k & 1 ? mypow(mypow(2, p - 2, p), r - l, p) : 1;
  int t = mypow(2, l, p - 1), ans;
  t = mypow(k, t, p);
  if ((t - 1) % p == 0)
    ans = mypow(2, r - l + 1, p);
  else {
    int c = mypow(2, r - l + 1, p - 1);
    c = mypow(t, c, p);
    ans = (long long int)(c + p - 1) * mypow(t + p - 1, p - 2, p) % p;
  }
  if (k & 1) ans = (long long int)ans * mypow(mypow(2, p - 2, p), r - l, p) % p;
  return ans;
}
int main() {
  int T = getint();
  while (T--) printf("%d\n", work());
}
