#include <bits/stdc++.h>
using namespace std;
#define null NULL
#define ll long long int
#define pb push_back
#define pob pop_back


// Function Declarations
ll grt2(ll n);
ll divi(ll n);
ll gcd(ll a, ll b);
ll count_2(ll n);
ll lcm_calc(ll a, ll b);
void run();
ll nextPrime(ll N);
bool isPrime(ll n);
ll ncr(ll n, ll r);
// End Function Declarations

// Main Function
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(null);
    cout.tie(null);
    
    // run();
    ll t;
    cin>>t;
    while(t-- > 0)
    {
        run();
    }
}

void run()
{
    ll p, a, b, c;
    cin>>p>>a>>b>>c;
    if(p%a != 0)
        a = a - (p%a);
    else
    {
        cout<<"0"<<endl;
        return;
    }
    if(p%b != 0)
        b = b - (p%b);
    else
    {
        cout<<"0"<<endl;
        return;
    }
    if(p%c != 0)
        c = c - (p%c);
    else
    {
        cout<<"0"<<endl;
        return;
    }
    cout<<min(a, min(b, c))<<endl;
}


bool isPrime(ll n)  
{  
    if (n <= 1)  return false;  
    if (n <= 3)  return true;  
    if (n%2 == 0 || n%3 == 0) return false;
    if(n%2 == 0 && n%3 == 0) return false;
    if(n%2 == 0 && n%5 == 0) return false;
    
    for (ll i=5; i*i<=n; i=i+6)  
        if (n%i == 0 || n%(i+2) == 0)  
           return false;  
    
    return true;  
}  

ll ncr(ll n, ll r)
{
    if(r > n - r) r = n - r;
    ll ans = 1;
    ll i;

    for(i = 1; i <= r; i++) {
        ans *= n - r + i;
        ans /= i;
    }

    return ans;
}
  
ll nextPrime(ll N) 
{ 
    if (N <= 1) 
        return 2; 
  
    ll prime = N; 
    bool found = false; 
    while (!found) { 
        prime++; 
  
        if (isPrime(prime)) 
            found = true; 
    } 
  
    return prime; 
} 

ll count_2(ll n) 
{ 
    ll cnt = 0; 
    while (1) { 
        if(n%2==0)
        {
            cnt++;
            n = n/2;
        }
        else
        {
            break;
        }
    }
    return cnt; 
} 

ll lcm_calc(ll a, ll b)
{
    return (a / gcd(a, b)) * b;
}

ll gcd(ll a, ll b) 
{ 
	if (a == 0) 
		return b; 
	return gcd(b % a, a); 
}

ll divi(ll n) 
{ 
    
    for (ll i=1; i<=sqrt(n); i++) 
    { 
        if (n%i == 0) 
        {
            return i;
        } 
    } 
} 

ll grt2(ll n) 
{ 
   ll p = (ll)log2(n); 
   return p;  
}

// End