#include<bits/stdc++.h>
#define endl "\n"
#define ll long long
#define eb emplace_back
#define pb push_back
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(),(x).end()
#define MA 1e+18
#define unique_arr(x) (x).resize(distance((x).begin(),unique(all(x))))//First sort the array
int va=1e9+7;
ll val[200007]={0};
using namespace std;
/*
 *-Minimum Value in map not the (minimum key value) minimum second value
 *auto it = min_element(mp.begin(), mp.end(),[](const auto& l, const auto& r) { return l.second < r.second; }); 
 *auto it = min_element(mp.begin(), mp.end(),[](auto l,auto r){return l.second<r.second;});
 *-If one value in pair is known and you have to find other
 *pair<int,string>//string is known you have to find int
 *auto it=find_if(stocks.begin(), stocks.end(),[name](auto p){ return p.second == name; });
 *lower_bound(all(a),x)-a.begin(); it gives x ke barabar ya just usse se choti value ka index
*/
//Conditional Operator (condition?true part:false part) eg : cout<<(y<=3?"YES":"NO")<<endl;
//string s(3,'1');
// if number of elements in array >10^5 then declare global array.
//****Always do upsolving******
ll getmul(ll n){ll int k{0};while(n>0){k+=n%10;n=n/10;}return k;}//Sum OF n DIGITS 
int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
#ifndef ONLINE_JUDGE 
    freopen("input1.txt", "r", stdin); 
    freopen("output1.txt", "w", stdout); 
#endif 
    int t{1};  
    cin>>t;
    while(t--){
        ll p,a,b,c;
        cin>>p>>a>>b>>c;
        if(p%a==0||p%b==0||p%c==0) {
            cout<<"0"<<endl;
            continue;
        }
        ll x=p%a,y=p%b,z=p%c;
        ll ans=min({a-x,b-y,c-z});
        cout<<ans<<endl;
    }
 return 0;
}
