#include <bits/stdc++.h>
using namespace std;
int i, j, n, m, T;
long long k, l, r, p, Gcd, an;
inline long long pow(long long x, long long y, long long mo) {
  x %= mo;
  if (!y) return 1;
  if (!x) return 0;
  long long an = 1;
  for (; y; y >>= 1) {
    if (y & 1) an = an * x % mo;
    x = x * x % mo;
  }
  return an;
}
int main() {
  scanf("%d", &T);
  for (; T; T--) {
    scanf("%I64d%I64d%I64d%I64d", &k, &l, &r, &p);
    if (k & 1 && r > l)
      Gcd = 2;
    else
      Gcd = 1;
    if (p == 2) {
      if (k & 1)
        printf("0\n");
      else
        printf("1\n");
      continue;
    }
    long long A = pow(2, l, p - 1);
    long long B = pow(k, A, p);
    if (l && k % p == 0) B = 0;
    B = (B + p - 1) % p;
    if (!B)
      an = pow(2, r - l + 1, p);
    else {
      B = pow(B, p - 2, p);
      an = ((k % p == 0 ? 0 : pow(k, pow(2, r + 1, p - 1), p)) - 1) * B % p;
      if (an < 0) an += p;
    }
    an = an * pow(pow(Gcd, p - 2, p), r - l, p) % p;
    printf("%I64d\n", an);
  }
  return 0;
}
