#include <bits/stdc++.h>
using namespace std;
inline void read(int &x) {
  int v = 0, f = 1;
  char c = getchar();
  while (!isdigit(c) && c != '-') c = getchar();
  if (c == '-')
    f = -1;
  else
    v = (c & 15);
  while (isdigit(c = getchar())) v = (v << 1) + (v << 3) + (c & 15);
  x = v * f;
}
inline void read(long long &x) {
  long long v = 0ll, f = 1ll;
  char c = getchar();
  while (!isdigit(c) && c != '-') c = getchar();
  if (c == '-')
    f = -1;
  else
    v = (c & 15);
  while (isdigit(c = getchar())) v = (v << 1) + (v << 3) + (c & 15);
  x = v * f;
}
inline void readc(char &x) {
  char c;
  while (((c = getchar()) == ' ') || c == '\n')
    ;
  x = c;
}
inline void writes(string s) { puts(s.c_str()); }
inline void writeln() { writes(""); }
inline void writei(int x) {
  if (x < 0) {
    putchar('-');
    x = abs(x);
  }
  if (!x) putchar('0');
  char a[25];
  int top = 0;
  while (x) {
    a[++top] = (x % 10) + '0';
    x /= 10;
  }
  while (top) {
    putchar(a[top]);
    top--;
  }
}
inline void writell(long long x) {
  if (x < 0) {
    putchar('-');
    x = abs(x);
  }
  if (!x) putchar('0');
  char a[25];
  int top = 0;
  while (x) {
    a[++top] = (x % 10) + '0';
    x /= 10;
  }
  while (top) {
    putchar(a[top]);
    top--;
  }
}
long long p, q, a, b, i, j, t, ans, l, r, mid;
long long exgcd(long long n, long long m, long long &x, long long &y) {
  if (!m) {
    x = 1;
    y = 0;
    return n;
  }
  long long ans = exgcd(m, n % m, y, x);
  y -= n / m * x;
  return ans;
}
long long itlc(long long a, long long b, long long c, long long n) {
  if (n < 0) return 0;
  if (!a || !n) return (n + 1) * (b / c);
  if (a >= c || b >= c) {
    return itlc(a % c, b % c, c, n) + (n * (n + 1) / 2) * (a / c) +
           (n + 1) * (b / c);
  }
  long long l = (a * n + b) / c;
  return n * l - itlc(c, c - b - 1, a, l - 1);
}
int main() {
  read(t);
  while (t--) {
    read(a);
    read(b);
    read(p);
    read(q);
    l = -1;
    ans = r = q;
    while (l < r) {
      mid = (l + r + 1) / 2;
      long long tl = q - mid, tr = q + mid + 1;
      long long t = 0;
      t += itlc(p * 2, q * 2 - tl, q * 2, b);
      t -= itlc(p * 2, q * 2 - tr, q * 2, b);
      t -= itlc(p * 2, q * 2 - tl, q * 2, a - 1);
      t += itlc(p * 2, q * 2 - tr, q * 2, a - 1);
      if (t > 0) {
        ans = mid;
        r = mid - 1;
      } else {
        l = mid;
      }
    }
    long long x, y, sss = 0x1bbbbbbbbbbbbbbbll;
    long long g = exgcd(p * 2, q * 2, x, y);
    if ((q + ans) % g == 0) {
      long long xx = (q + ans) / g * x;
      xx += (a - xx) / (q * 2 / g) * (q * 2 / g);
      xx = ((xx - a) % (q * 2 / g) + (q * 2 / g)) % (q * 2 / g) + a;
      sss = min(sss, xx);
    }
    if ((q - ans) % g == 0) {
      long long xx = (q - ans) / g * x;
      xx += (a - xx) / (q * 2 / g) * (q * 2 / g);
      xx = ((xx - a) % (q * 2 / g) + (q * 2 / g)) % (q * 2 / g) + a;
      sss = min(sss, xx);
    }
    printf("%I64d\n", sss);
  }
  return 0;
}
