#include <iostream>
#include <bits/stdc++.h>
using namespace std;
#define lli long long int

int main() {
  int T;
  cin >> T;

  for (int t=0; t<T; ++t) {
    lli p, a, b, c;
    cin >> p >> a >> b >> c;
    auto stime = [&p](lli x) {
      if (x == 0 || p%x == 0) return 0LL;
      lli d = p/x;
      return (d+1)*x - p;
    };
    lli ans = min(stime(a), min(stime(b), stime(c)));
    cout << ans << endl;
  }

  return 0;
}
