#include <bits/stdc++.h>
#define mp make_pair
#define pb push_back
#define sz size()
#define Beg begin()
#define End end()
using namespace std;
typedef long long ll;
typedef pair <int, int> pii;
typedef vector <int> vi;
typedef vector <long long> vll;
const int MOD = 1e9 + 7;
const int maxn = 2e5 + 7;
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    int tt;
    cin >> tt;
    while(tt--){
        ll p, a, b, c;
        cin >> p >> a >> b >> c;
        ll r1 = p / a + 1;
        if(p % a == 0)r1 = p / a;
        ll r2 = p / b + 1;
        if(p % b == 0)r2 = p / b;
        ll r3 = p / c + 1;
        if(p % c == 0)r3 = p / c;
        cout << min(r1 * a - p, min(r2 * b - p, r3 * c - p)) << '\n';
    }
    return 0;
}