#include <bits/stdc++.h>
using namespace std;
const double PI = 2.0 * acos(0.0);
inline int getInt() {
  int x;
  scanf("%d", &x);
  return x;
}
inline long long getLL() {
  long long x;
  scanf("%lld", &x);
  return x;
};
inline int NUM(char c) { return (int)c - 48; }
inline char CHR(int n) { return (char)(n + 48); }
template <class T>
inline T MAX(T a, T b) {
  if (a > b) return a;
  return b;
}
template <class T>
inline T MIN(T a, T b) {
  if (a < b) return a;
  return b;
}
template <class T>
inline T ABS(T a) {
  if (a < 0) return -a;
  return a;
}
inline void OPEN(string s) {
  freopen((s + ".in").c_str(), "r", stdin);
  freopen((s + ".out").c_str(), "w", stdout);
}
long long BPM(long long a, long long b, long long MOD) {
  if (a == 0) return 0;
  if (b == 0) return 1;
  if (b % 2 == 0) {
    long long x = BPM(a, b / 2, MOD);
    return x * x % MOD;
  }
  return a * BPM(a, b - 1, MOD) % MOD;
}
long long cnt(long long X, long long P, long long MOD) {
  if (P == 0) return 1;
  long long tmp = cnt(X * X % MOD, P - 1, MOD);
  return (tmp + tmp * X % MOD) % MOD;
}
long long MOD;
long long K, L, R;
int main() {
  int nTC;
  cin >> nTC;
  while (nTC--) {
    cin >> K >> L >> R >> MOD;
    if (MOD == 2 && K % 2 == 1) {
      cout << 0 << endl;
    } else if (MOD == 2) {
      cout << 1 << endl;
    } else {
      long long b = BPM(2, L, MOD - 1);
      long long X = BPM(K % MOD, b, MOD);
      long long p = BPM(2, R - L + 1, MOD - 1);
      long long ret;
      if (X == 0)
        ret = 1;
      else if (X == 1)
        ret = BPM(2, R - L + 1, MOD);
      else {
        ret = (BPM(X, p, MOD) - 1 + MOD) % MOD;
        ret *= (BPM((MOD + (X - 1) % MOD) % MOD, MOD - 2, MOD));
        ret %= MOD;
      }
      if (K % 2 == 1) {
        ret = ret * BPM(BPM(2, MOD - 2, MOD), R - L, MOD) % MOD;
      }
      cout << ret << endl;
    }
  }
  return 0;
}
