/*.........I don't matter............*/
//Coded by Aman Bharti (ECE 2k18) Nit Patna
#pragma GCC optimize("Ofast", "unroll-loops", "no-stack-protector")
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define mod 100000000


int32_t main()
{
  ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);

//   assert(freopen("soln.in","r",stdin));
//   assert(freopen("soln.out","w",stdout));

  int test=1;
  cin>>test;

  while(test--){
      	int p,a,b,c;
	    cin>>p>>a>>b>>c;
        cout<<min({(a-(p%a))%a,(b-(p%b))%b,(c-(p%c))%c})<<endl;
  }

  cerr<<endl<<"Time: "<<(clock() * 1000. / CLOCKS_PER_SEC)<<" ms"<<endl;
  return 0;
}