#include <bits/stdc++.h>
using namespace std;
unsigned long long pow(unsigned long long a, unsigned long long n,
                       unsigned long long m) {
  if (n == 0) return 1;
  if (n % 2 == 0) {
    unsigned long long ans = pow(a, n / 2, m);
    return (ans * ans) % m;
  } else
    return (pow(a, n - 1, m) * a) % m;
}
int main() {
  int t;
  unsigned long long k, l, r, p, a, c, ans;
  scanf("%d", &t);
  for (int i = 0; i < t; i++) {
    scanf("%I64u %I64u %I64u %I64u", &k, &l, &r, &p);
    a = pow(k, pow(2, l, p - 1), p);
    c = pow(2, r - l + 1, p - 1);
    ans = (pow(a - 1, p - 2, p) * (pow(a, c, p) + p - 1)) % p;
    if (a == 1) ans = pow(2, r - l + 1, p) % p;
    if (k % p == 0) ans = 1;
    if (k % 2 == 1) ans = (ans * pow(2, (p - 2) * ((r - l) % (p - 1)), p)) % p;
    printf("%I64u\n", ans);
  }
}
