#include <bits/stdc++.h>
using namespace std;
long long n, m, i, j, k, x, y, z, p, l, r, ans;
long long Left, Right;
long long fpm(long long F, long long FF, long long p) {
  if (F == 0) return 0;
  if (FF == 0) return 1;
  long long ret = 1;
  for (; FF; FF >>= 1, F = F * F % p)
    if (FF & 1) ret = ret * F % p;
  return ret;
}
long long Inv(long long x) { return fpm(x, p - 2, p); }
long long f(long long x) {
  if (k == 0) return 0;
  return fpm(k, fpm(2, x, p - 1), p);
}
int main() {
  ios ::sync_with_stdio(false);
  cin >> n;
  while (n--) {
    cin >> k >> l >> r >> p;
    if (k == 1)
      cout << 2 % p << endl;
    else if (p == 2)
      cout << 1 - k % 2 << endl;
    else {
      if (k & 1)
        ans = fpm(Inv(2), r - l, p);
      else
        ans = 1;
      k %= p;
      Left = f(l), Right = f(r + 1);
      if (Left == 1)
        cout << fpm(2, r - l + 1, p) * ans % p << endl;
      else
        cout << ((Right - 1) * Inv(Left - 1) % p) * ans % p << endl;
    }
  }
  return 0;
}
