#include <bits/stdc++.h>
using namespace std;
long long k, l, r, p;
long long Pow(long long a, long long b, long long p) {
  long long d = 1;
  if (!a) return 0;
  if (!b) return 1;
  for (; b;
       d = (b & 1) ? (long long)d * a % p : d, a = (long long)a * a % p, b /= 2)
    ;
  return d;
}
void solve() {
  cin >> k >> l >> r >> p;
  if (k == 1) {
    cout << 2 % p << endl;
    return;
  }
  long long CC = (k & 1) ? Pow(Pow(2, p - 2, p), r - l, p) : 1;
  k %= p;
  long long x = Pow(k, Pow(2, r + 1, p - 1), p),
            y = Pow(k, Pow(2, l, p - 1), p);
  if (y == 1)
    CC = (long long)CC * Pow(2, r - l + 1, p) % p;
  else
    CC = (long long)CC * (x - 1) % p * Pow(y - 1, p - 2, p) % p;
  cout << (CC + p) % p << endl;
}
int main() {
  int test;
  scanf("%d", &test);
  while (test) solve(), --test;
  fclose(stdin);
  fclose(stdout);
  return 0;
}
