#include <bits/stdc++.h>
using namespace std;
int power(int a, long long b, int mo) {
  int c = 1;
  while (b) {
    if (b & 1) c = 1LL * c * a % mo;
    b >>= 1;
    a = 1LL * a * a % mo;
  }
  return c;
}
int K, mo;
int main() {
  int T;
  scanf("%d", &T);
  for (int i = 1; i <= T; i++) {
    long long l, r;
    scanf("%d%I64d%I64d%d", &K, &l, &r, &mo);
    if (mo == 2) {
      printf("%d\n", !(K & 1));
      continue;
    }
    int x, y, ans;
    if (K % mo == 0)
      x = y = mo - 1;
    else
      x = power(K, power(2, r + 1, mo - 1), mo) - 1,
      y = power(K, power(2, l, mo - 1), mo) - 1;
    if (x < 0) x += mo;
    if (y < 0) y += mo;
    if (y == 0)
      ans = power(2, r - l + 1, mo);
    else
      ans = 1LL * x * power(y, mo - 2, mo) % mo;
    printf(
        "%I64d\n",
        1LL * ans * (K & 1 ? power(power(2, r - l, mo), mo - 2, mo) : 1) % mo);
  }
}
