#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <utility>
#include <algorithm>
#include <cmath>
#include <climits>
#include <iomanip>
#include <queue>
#include <stack>
#include <ctype.h>

using namespace std;

typedef long long ll;

const int INF = (1<<30)-1;
const ll LINF = (1LL<<60)-1;

#define rep(i, n) for (int i = 0; i < n; i++)

template<class T> 
bool chmax(T &a, T b) {if (a < b) {a = b;return true;}else return false;}

template<class T> 
bool chmin(T &a, T b) {if (a > b) {a = b;return true;}else return false;}

//コーナーケースに気をつけろ！！
int main() {
    int t;  cin >> t;
    while (t--) {
        ll p, a, b, c, ans = LINF; cin >> p >> a >> b >> c;
        chmin(ans, (p+a-1)/a*a-p);
        chmin(ans, (p+b-1)/b*b-p);
        chmin(ans, (p+c-1)/c*c-p);
        cout << ans << endl;
    }
    return 0;
}

//小数点精度
//cout << fixed << std::setprecision(15) << y << endl;