#include <bits/stdc++.h>
using namespace std;
const long long N = 1e5 + 5;
const long long mod = 1e9 + 7;
const long long INF = 0x7f7f7f7f7f7f7f7f;
const int INFi = 0x7f7f7f7f;
long long l, r, k, p, ans;
long long fastmod(long long x, long long y, long long mod) {
  long long res = 1;
  while (y) {
    if (y & 1) res = res * x % mod;
    x = x * x % mod;
    y /= 2;
  }
  return res;
}
void solve() {
  cin >> k >> l >> r >> p;
  if (p == 2) {
    cout << 1 - (k & 1) << "\n";
  } else {
    if (k % p == 0) {
      ans = 1;
      if (k & 1) {
        ans = ans * fastmod(fastmod(2, r - l, p), p - 2, p) % p;
      }
      cout << ans << "\n";
    } else {
      long long x = (fastmod(k, fastmod(2, r + 1, p - 1), p) + p - 1) % p;
      long long y = (fastmod(k, fastmod(2, l, p - 1), p) + p - 1) % p;
      if (y)
        ans = x * fastmod(y, p - 2, p) % p;
      else
        ans = fastmod(2, r - l + 1, p);
      if (k & 1) {
        ans = ans * fastmod(fastmod(2, r - l, p), p - 2, p) % p;
      }
      cout << ans << "\n";
    }
  }
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cout << fixed;
  cout << setprecision(15);
  ;
  int test = 1;
  cin >> test;
  for (int i = 1; i <= test; i++) {
    solve();
  }
}
