#include <bits/stdc++.h>
using namespace std;
template <class T>
inline void setmax(T &a, T b) {
  if (b > a) a = b;
}
template <class T>
inline void setmin(T &a, T b) {
  if (b < a) a = b;
}
int power(long long a, long long b, int p) {
  if (!b) return 1;
  long long ans = power(a, b >> 1, p);
  ans = (ans * ans) % p;
  if (b & 1) ans = (ans * a) % p;
  return ans;
}
int inv(int a, int p) { return power(a, p - 2, p); }
void div(long long &a, int q, int p) { a = (a * inv(q, p)) % p; }
int main(void) {
  int t;
  cin >> t;
  for (; t; t--) {
    int k, p;
    long long l, r;
    long long ans;
    cin >> k >> l >> r >> p;
    if (p == 2) {
      if (k & 1)
        cout << 0 << endl;
      else
        cout << 1 << endl;
      continue;
    }
    if (k % p == 0) {
      ans = 1;
    } else if (k % p == 1) {
      ans = power(2, r - l + 1, p);
    } else {
      int a = power(k, power(2, l, p - 1), p);
      if (a == 1) {
        ans = power(2, r - l + 1, p);
      } else {
        ans = (power(a, power(2, r - l + 1, p - 1), p) + p - 1) % p;
        div(ans, (a + p - 1) % p, p);
      }
    }
    if (k & 1) {
      ans *= power(inv(2, p), r - l, p);
      ans %= p;
    }
    cout << ans << endl;
  }
  return 0;
}
