#include <bits/stdc++.h>
using namespace std; 
 
#define FASTIO           ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define TEST             ll Test ; cin >> Test; while
#define TEST2            int Test = 1; while
#define READ             freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
#define INP(a, n)        for(ll i=0;i<(ll)n;i++) cin>>a[i] ;
#define INPA(a, n)       ll a[n]; for(ll i=0;i<(ll)n;i++) cin>>a[i] ;
#define INPV(a, n)       ll TrT; for(int i=0;i<(ll)n;i++){cin>>TrT; a.push_back(TrT);}
#define OUT(a, n)        for(ll i=0;i<(ll)n;i++)cout<<a[i]<<" ";
#define forp(i,a,b)      for(ll i=a;i<(ll)b;i++)
#define fore(i,a,b)      for(ll i=a;i<=(ll)b;i++)
#define fora(x)          for(auto &it: x)
#define INF              LLONG_MAX
#define sz               size()
#define len              length()
#define beg              begin()
#define en               end()
#define all(x)           x.beg,x.en
#define ff               first
#define ss               second
#define pb               push_back
#define pp               pop_back
#define lb               lower_bound
#define ub               upper_bound
#define N                '\n'
#define YES(n)           cout << ((n) ? "YES" : "NO") << "\n" ;
#define Yes(n)           cout << ((n) ? "Yes" : "No") << "\n" ;
#define fix(f,n)         fixed << setprecision(n) << f 
#define M                1000000007
#define MM               998244353

#define TRACE

#ifdef TRACE
    #define d(...) __f(#__VA_ARGS__, __VA_ARGS__)
    template <typename Arg1>
        void __f(const char* name, Arg1&& arg1) { cout << name << " = " << arg1 << endl; }
    template <typename Arg1, typename... Args>
        void __f( const char* names, Arg1&& arg1, Args&&... args) {const char* comma = strchr(names + 1, ','); cout.write(names, comma - names) << " = " << arg1 << " "; __f(comma + 1, args...); }
#else
    #define d(...)
#endif
 
typedef long long int ll;
typedef long double ld;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<vector<int>> vvi;
typedef vector<vector<ll>> vvll;
typedef vector<vector<ld>> vvld;
typedef pair<ll, ll> pll;
typedef vector<int> vi ;
typedef vector<pair<int, int>> vpi;
typedef vector<pair<ll,ll> > vpll;



void solve() {
    ll p, a, b, c, temp, ans = INF;
    cin >> p;
    ll v[3];
    forp(i, 0, 3) cin >> v[i];
    forp(i, 0, 3) {
        temp = p/v[i];
        if(p % v[i] != 0) temp++;
        ll x = temp * v[i];
        // d(x);
        ans = min(x - p, ans);
    }
    cout << ans << N;
}

int main() { FASTIO 
    #ifndef ONLINE_JUDGE
        // READ
    #endif 
    TEST(Test--)
    {	
        solve();
    }
    return 0;
}
