#include <bits/stdc++.h>
using namespace std;
 
#define lli long long int
#define vtt vector<long long int>
#define pb push_back
#define mp make_pair
#define ll long long
#define lb lower_bound
#define ub upper_bound
#define pb push_back
#define endl "\n"
#define all v.begin(),v.end()
#define f(i,s,e) for(long long int i=s;i<e;i++)
#define fc(i,s,e) for(long long int i=s;i<=e;i++)
#define fr(i,e,s) for(long long int i=e-1;i>=s;i--)
typedef pair<int,int> pii;
typedef pair<long long,long long> pll;

lli maxxx(lli n1,lli n2,lli n3)
{
    lli maxim=0;
    if(n1 >= n2 && n1 >= n3) maxim=n1;
    else if(n2 >= n1 && n2 >= n3) maxim=n2;  
    else if(n3 >= n1 && n3 >= n2) maxim=n3;
    return maxim;
}
lli minnn(lli n1,lli n2,lli n3)
{
    lli maxim=0;
    if(n1 <= n2 && n1 <= n3) maxim=n1;
    else if(n2 <= n1 && n2 <= n3) maxim=n2;  
    else if(n3 <= n1 && n3 <= n2) maxim=n3;
    return maxim;
}

lli ceil(lli a,lli x)
{
    if(a%x==0) return a/x;
    else return a/x+1;
}

vector<lli> CALCfactor(lli n)
{
    vector<lli> factor;
    fc(i,1,sqrt(n))
    {
        if(n%i==0){
            if(n/i==i)
            factor.pb(i);
            else
            factor.pb(i),factor.pb(n/i);}
    }
    return factor;
}
vector<lli> sieve(lli n)
{    
    vector<lli> seive(n+1,1),prime;
    for(int i=2;i*i<=n;i++)
    {if(seive[i]==1)
    for(int j=i*i;j<=n;j+=i) seive[j]=0;}
    fc(i,2,n)
    {if(seive[i]==1)prime.pb(i);}
    return prime;
}
vector<lli> CALCprimeFACTOR(lli n)
{  
    vector<lli> ans; 
    while (n % 2 == 0)  
    {  ans.pb(2);  n = n/2;  }  
    for (int i = 3; i <= sqrt(n); i = i + 2)  
    {  while (n % i == 0)  
        {  ans.pb(i);  n = n/i;  }  
    }    
    if (n > 2)  ans.pb(n);  
        return ans;
}
//template ends
 
int main()
{
    ios_base::sync_with_stdio(false); 
    cin.tie(NULL);
    cout.tie(NULL);
    
    lli t;
    cin>>t;
    while(t--)
    {
        lli p,a,b,c;
        cin>>p>>a>>b>>c;
        lli x=0,y=0,z=0;
        x=p%a!=0?(a*(p/a+1))-p:0;
        y=p%b!=0?(b*(p/b+1))-p:0;
        z=p%c!=0?(c*(p/c+1))-p:0;
        lli minn=minnn(x,y,z);
        cout<<minn<<"\n";
        
    }
}