#include <bits/stdc++.h>
using namespace std;
int T, k, p;
long long l, r;
int pw(int base, long long n, int mod) {
  if (!n) return 1;
  int ret = pw(base, n / 2, mod);
  ret = 1LL * ret * ret % mod;
  if (n & 1) ret = 1LL * ret * base % mod;
  return ret;
}
int main() {
  scanf("%d", &T);
  while (T--) {
    scanf("%d%lld%lld%d", &k, &l, &r, &p);
    if (p == 2) {
      if (k & 1)
        puts("0");
      else
        puts("1");
      continue;
    }
    int n = pw(2, l, p - 1);
    if (!n) n = p - 1;
    int m = (pw(k, n, p) + p - 1) % p;
    int x = pw(2, r - l, p);
    if (m == 0) {
      if (k & 1)
        puts("2");
      else
        printf("%d\n", x * 2 % p);
      continue;
    }
    int a = pw(2, r + 1, p - 1);
    if (!a) a = p - 1;
    int b = (pw(k, a, p) + p - 1) % p;
    int y = pw(x, p - 2, p);
    int z = pw(m, p - 2, p);
    if (k & 1)
      printf("%d\n", 1LL * b * y % p * z % p);
    else
      printf("%d\n", 1LL * b * z % p);
  }
}
