#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int n, kk, P;
ll l, r;
ll qpow(ll a, ll b, ll p = P) {
  if (!a) return 0;
  ll ret = 1;
  while (b) {
    if (b & 1) ret = ret * a % p;
    a = a * a % p;
    b >>= 1;
  }
  return ret;
}
inline ll inv(ll num) { return qpow(num, P - 2); }
int main() {
  ios::sync_with_stdio(false);
  cin >> n;
  for (int _ = 1; _ <= n; _++) {
    cin >> kk >> l >> r >> P;
    if (P == 2) {
      cout << !(kk % 2) << endl;
      continue;
    }
    ll tmp = kk % 2 ? inv(qpow(2, r - l)) : 1;
    kk %= P;
    ll d = (qpow(kk, qpow(2, l, P - 1)) + P - 1) % P;
    if (!d)
      cout << qpow(2, r - l + 1) * tmp % P << endl;
    else
      cout << (qpow(kk, qpow(2, r + 1, P - 1)) + P - 1) * qpow(d, P - 2) % P *
                  tmp % P
           << endl;
  }
  return 0;
}
