#include <bits/stdc++.h>
using namespace std;
inline char gc() {
  static char buf[100000], *p1 = buf, *p2 = buf;
  return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 100000, stdin), p1 == p2)
             ? EOF
             : *p1++;
}
inline long long read() {
  long long x = 0;
  char ch = getchar();
  bool positive = 1;
  for (; !isdigit(ch); ch = getchar())
    if (ch == '-') positive = 0;
  for (; isdigit(ch); ch = getchar()) x = x * 10 + ch - '0';
  return positive ? x : -x;
}
inline void write(long long a) {
  if (a < 0) {
    a = -a;
    putchar('-');
  }
  if (a >= 10) write(a / 10);
  putchar('0' + a % 10);
}
inline void writeln(long long a) {
  write(a);
  puts("");
}
inline void wri(long long a) {
  write(a);
  putchar(' ');
}
long long rnd() {
  unsigned long long ans = 0;
  for (int i = (int)(0); i <= (int)(4); i++) ans = ans << 15 ^ rand();
  return ans % ((unsigned long long)1 << 63);
}
const int B = 32000;
long long a, b, p, q, qq, mn, ans;
void solve(int i) {
  long long t = abs(i * p % qq - q);
  if (t < mn || t == mn && i < ans) {
    mn = t;
    ans = i;
  }
}
pair<long long, long long> to[B];
int main() {
  int T = read();
  while (T--) {
    a = read(), b = read() + 1, p = read() * 2, q = read(), qq = q << 1;
    mn = 2e9;
    if (b - a <= 2 * B) {
      for (int i = (int)(a); i <= (int)(b - 1); i++) solve(i);
      writeln(ans);
    } else {
      for (int i = (int)(a); i <= (int)(a / B * B + B - 1); i++) solve(i);
      int tot = 0;
      for (int i = (int)(0); i <= (int)(B - 1); i++)
        to[tot++] = make_pair(i * p % qq, i);
      sort(to, to + tot);
      int tt = 0;
      for (int i = (int)(1); i <= (int)(tot - 1); i++)
        if (to[i].first != to[tt].first) to[++tt] = to[i];
      tot = tt + 1;
      for (int i = a / B * B + B; i < b / B * B; i += B) {
        long long t = i * p % qq;
        int pos = lower_bound(to, to + tot,
                              make_pair((q + qq - t) % qq, (long long)0)) -
                  to;
        solve(i + to[(pos + tot - 1) % tot].second);
        solve(i + to[pos % tot].second);
      }
      for (int i = (int)(b / B * B); i <= (int)(b - 1); i++) solve(i);
      writeln(ans);
    }
  }
}
