#include <bits/stdc++.h>
int T, k, p;
long long l, r, ans;
long long power(long long base, long long e, int p) {
  if (e == 0) return base ? 1 : 0;
  long long ret = power(base, e >> 1, p);
  ret = ret * ret % p;
  return (e & 1) ? ret * base % p : ret;
}
int main() {
  for (scanf("%d", &T); T--;) {
    scanf("%d%I64d%I64d%d", &k, &l, &r, &p);
    if (k == 1) {
      printf("%d\n", 2 % p);
      continue;
    }
    if (k & 1)
      ans = power(power(2, p - 2, p), r - l, p);
    else
      ans = 1;
    k %= p;
    long long eA = power(2, r + 1, p - 1), eB = power(2, l, p - 1),
              A = power(k, eA, p), B = power(k, eB, p);
    if (B == 1)
      ans = ans * power(2, r - l + 1, p) % p;
    else
      ans = ans * ((A - 1) * power(B - 1, p - 2, p) % p) % p;
    printf("%d\n", (int)(ans + p) % p);
  }
}
