#include <bits/stdc++.h>
using namespace std;
int n;
long long k, l, r, p;
long long QuickPow(long long a, long long b) {
  a %= p;
  long long c = 1LL;
  for (; b; b >>= 1, a = a * a % p) (b & 1) ? c = (c * a) % p : 0;
  return c;
}
long long QuickPow2(long long a, long long b) {
  a %= p - 1LL;
  long long c = 1LL;
  for (; b; b >>= 1, a = a * a % (p - 1LL))
    (b & 1) ? c = (c * a) % (p - 1LL) : 0;
  if (c == 0) c = p - 1LL;
  return c;
}
int main() {
  cin >> n;
  for (int i = 1; i <= n; ++i) {
    cin >> k >> l >> r >> p;
    if (p == 2) {
      cout << ((k & 1) ^ 1) << endl;
      continue;
    }
    if (k == 1) {
      cout << 2 << endl;
      continue;
    }
    long long a = QuickPow(k, QuickPow2(2LL, l)), b;
    if (a == 0)
      b = 1;
    else if (a == 1)
      b = QuickPow(2LL, r - l + 1);
    else
      b = ((QuickPow(a, QuickPow2(2LL, r - l + 1)) + p - 1) % p) *
          QuickPow(a - 1, p - 2) % p;
    if (k & 1)
      cout << b * QuickPow(QuickPow(2LL, p - 2), r - l) % p << endl;
    else
      cout << b << endl;
  }
  return 0;
}
