#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
#define IO(file) freopen(file ".in", "r", stdin); freopen(file ".out", "w", stdout)
#define FAST_IO ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define endl "\n"
#define F first
#define S second
#define pb push_back
#define all(obj) obj.begin(), obj.end()
#define print(obj) for(auto obj_el: obj) cout << obj_el << " "; cout << endl
int const INF = 1e9;
int const MAXN = 2e5 + 5;
ll const MAX = 1e18;
ll const MOD = 1e9 + 7;
ll solve(ll p, ll x) {
    if(p <= x) {
        return x - p;
    }
    ll lo = 1, hi = 1 + (MAX / x), mid = 0, ans = 0;
    while(hi - lo > 1) {
        mid = lo + (hi - lo) / 2;
        if(mid * x < p) {
            lo = mid;
        }
        else {
            hi = mid - 1;
        }
    }
    if((lo + 1) * x>= p) {
        ans = lo + 1;
    }
    else {
        ans = hi + 1;
    }
    return ans * x - p;
}
int main() {
    int T;
    cin >> T;
    while(T--) {
        ll p, a, b, c;
        cin >> p >> a >> b >> c;
        cout << min(solve(p, a), min(solve(p, b), solve(p, c))) << endl;
    }
}
