#include <bits/stdc++.h>
using namespace std;
void canhazfast() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  cout.tie(nullptr);
}
template <typename T>
T gcd(T a, T b) {
  return b ? gcd(b, a % b) : a;
}
template <typename T>
T extgcd(T a, T b, T &x, T &y) {
  T x0 = 1, y0 = 0, x1 = 0, y1 = 1;
  while (b) {
    T q = a / b;
    a %= b;
    swap(a, b);
    x0 -= q * x1;
    swap(x0, x1);
    y0 -= q * y1;
    swap(y0, y1);
  }
  x = x0;
  y = y0;
  return a;
}
int ctz(unsigned x) { return __builtin_ctz(x); }
int ctzll(unsigned long long x) { return __builtin_ctzll(x); }
int clz(unsigned x) { return __builtin_clz(x); }
int clzll(unsigned long long x) { return __builtin_clzll(x); }
int popcnt(unsigned x) { return __builtin_popcount(x); }
int popcntll(unsigned long long x) { return __builtin_popcountll(x); }
int bsr(unsigned x) { return 31 ^ clz(x); }
int bsrll(unsigned long long x) { return 63 ^ clzll(x); }
unsigned add(unsigned a, unsigned b, unsigned m) {
  return a + b < m ? a + b : a + b - m;
}
unsigned sub(unsigned a, unsigned b, unsigned m) {
  return a < b ? a + m - b : a - b;
}
unsigned g(unsigned x, unsigned p, unsigned q) {
  return 2ULL * x * p % (2 * q);
}
unsigned absdiff(unsigned a, unsigned b) { return max(a, b) - min(a, b); }
pair<unsigned, unsigned> gs[32768];
pair<unsigned, unsigned> nearest(unsigned k, unsigned q, unsigned v) {
  unsigned ia, da, ib, db;
  unsigned i = lower_bound(gs, gs + k, make_pair(v, 0U)) - gs;
  ia = i < k ? i : 0;
  da = absdiff(gs[ia].first, v);
  da = min(da, 2 * q - da);
  ib = i ? i - 1 : k - 1;
  db = absdiff(gs[ib].first, v);
  db = min(db, 2 * q - db);
  return make_pair(db, gs[ib].second) < make_pair(da, gs[ia].second) ? gs[ib]
                                                                     : gs[ia];
}
void solve() {
  unsigned a, b, p, q;
  unsigned t, d;
  pair<unsigned, unsigned> ans(1234567891, 0);
  cin >> a >> b >> p >> q;
  p %= q;
  d = gcd(q, p);
  if (p == 0 || d == q) return cout << a << '\n', void();
  p /= d;
  q /= d;
  b = min(b + 1, a + q);
  t = (unsigned)sqrt(b - a);
  for (unsigned i = 0; i < t; ++i) {
    unsigned x = i + a;
    gs[i].first = g(x, p, q);
    gs[i].second = x;
  }
  sort(gs, gs + t);
  d = g(t, p, q);
  for (unsigned dx = 0, dgx = 0, need = q; a + t <= b; a += t, dx += t) {
    pair<unsigned, unsigned> tmp = nearest(t, q, need);
    unsigned x = tmp.second + dx;
    unsigned gx = add(tmp.first, dgx, 2 * q);
    ans = min(ans, make_pair(absdiff(gx, q), x));
    dgx = add(dgx, d, 2 * q);
    need = sub(need, d, 2 * q);
  }
  for (; a < b; ++a) {
    unsigned ga = g(a, p, q);
    ans = min(ans, make_pair(absdiff(ga, q), a));
  }
  cout << ans.second << '\n';
}
int main() {
  canhazfast();
  int t;
  cin >> t;
  for (; t; --t) solve();
  return 0;
}
