#include <bits/stdc++.h>
using namespace std;
int mod;
inline int Add(int x) { return x >= mod ? x - mod : x; }
inline int Sub(int x) { return x < 0 ? x + mod : x; }
inline int Mul(int x, int y) { return (long long)x * y % mod; }
int Pow(int x, int y) {
  int z = 1;
  for (; y; y >>= 1) {
    if (y & 1) z = Mul(z, x);
    x = Mul(x, x);
  }
  return z;
}
int Pow(int x, long long y, int m) {
  int z = 1;
  for (; y; y >>= 1) {
    if (y & 1) z = (long long)z * x % m;
    x = (long long)x * x % m;
  }
  return z;
}
int Solve(int k, long long l, long long r) {
  k %= mod;
  int k2 = k ? Pow(k, Pow(2, l, mod - 1)) : 0;
  if (k2 == 1) {
    return Pow(2, (r - l) % (mod - 1));
  }
  int k3 = k2 ? Pow(k2, Pow(2, r - l, mod - 1)) : 0;
  return Mul(Sub(k3 - 1), Pow(Sub(k2 - 1), mod - 2));
}
int main(void) {
  int cas;
  scanf("%d", &cas);
  while (cas--) {
    int k;
    long long l, r;
    scanf("%d%lld%lld%d", &k, &l, &r, &mod);
    ++r;
    if (mod == 2) {
      puts(k & 1 ? "0" : "1");
      continue;
    }
    int ans = Solve(k, l, r);
    if (k & 1) {
      ans = Mul(ans, Pow(2, (mod - 1) - (r - l - 1) % (mod - 1)));
    }
    printf("%d\n", ans);
  }
  return 0;
}
