# include <bits/stdc++.h>
using namespace std;
# define ll long long
# define ld long double
# define pb push_back
# define pob pop_back
# define mp make_pair
# define all(x) x.begin(),x.end() 
# define ts to_string
int main()
{
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  int t;
 cin>>t;
  while(t--){
	ll p,a,b,c;
	cin>>p>>a>>b>>c;
	ll s,k,l;
	s= (a*((p+a-1)/a))-p;
    	k= (b*((p+b-1)/b))-p;
			l= (c*((p+c-1)/c))-p;
	ll ans= min(s,min(k,l));
	cout<<ans<<endl;
}	
  return 0;
}


