#include <bits/stdc++.h>
using namespace std;
inline long long binpow(long long n, long long p, long long mod) {
  if (p == 0) return 1LL;
  if (p & 1) return (n * binpow(n, p - 1, mod)) % mod;
  long long c = binpow(n, p / 2, mod);
  return (c * c) % mod;
}
int main() {
  int T;
  scanf("%d", &T);
  while (T--) {
    long long k, l, r, p;
    scanf("%lld%lld%lld%lld", &k, &l, &r, &p);
    if (k == 1) {
      printf("%lld\n", 2LL % p);
      continue;
    }
    if (p == 2) {
      if (k & 1)
        printf("0\n");
      else
        printf("1\n");
      continue;
    }
    long long ans;
    if (k % p == 0) {
      ans = 1;
      if (k & 1) ans = (ans * binpow(binpow(2LL, r - l, p), p - 2LL, p)) % p;
      printf("%lld\n", ans);
      continue;
    }
    long long a = binpow(k, binpow(2LL, l, p - 1), p);
    if (a == 1) {
      ans = binpow(2, r - l + 1, p);
      if (k & 1) {
        ans = (ans * (binpow(binpow(2LL, r - l, p), p - 2LL, p))) % p;
        printf("%lld\n", ans);
      } else
        printf("%lld\n", ans);
      continue;
    }
    ans = (binpow(a, binpow(2LL, r - l + 1, p - 1), p) - 1LL + p) % p;
    ans = (ans * binpow((a - 1 + p) % p, p - 2LL, p)) % p;
    if (k & 1) ans = (ans * binpow(binpow(2LL, r - l, p), p - 2LL, p)) % p;
    printf("%lld\n", ans);
  }
  return 0;
}
