#include <bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
    ios_base::sync_with_stdio(false);
    ll t;
    cin>>t;
    while(t--) {
    	ll p, a, b, c;
        cin>>p>>a>>b>>c;
        a = (a - (p % a)) % a;
        b = (b - (p % b)) % b;
        c = (c - (p % c)) % c;
        ll ans = min({a, b, c});
        cout<<ans<<"\n";
    }
}