#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define mod 1000000007
#define sprint ios_base::sync_with_stdio(false);cin.tie(NULL)

#define pb push_back
#define yes cout<<"YES\n"
#define no cout<<"NO\n"
#define new cout << "\n"

int main(){
    sprint;
    int t;
    cin >> t;
    while(t--){
        ll p,a,b,c,a1,b1,c1;
        cin >> p >> a >> b >> c;
        ll min1,min2,min3;
        if(p%a==0){
            min1=0;
        }else{
            min1=a-(p%a);
        }
        if(p%b==0){
            min2=0;
        }else{
            min2=b-(p%b);
        }
        if(p%c==0){
            min3=0;
        }else{
            min3=c-(p%c);
        }
        ll ans = min(min1,min(min2,min3));
        cout << ans << endl;
    }
}