#include<bits/stdc++.h>
using namespace std;
#define ps push_back
#define mk make_pair
#define ll long long int 

        bool isPrime(int n) 
{ 
    // Corner cases 
    if (n <= 1)  return false; 
    if (n <= 3)  return true; 
  
    // This is checked so that we can skip  
    // middle five numbers in below loop 
    if (n%2 == 0 || n%3 == 0) return false; 
  
    for (int i=5; i*i<=n; i=i+6) 
        if (n%i == 0 || n%(i+2) == 0) 
           return false; 
  
    return true; 
} 



int main()
{
	long long int T,t;
	cin>>T;
	for(t=0;t<T;t++)
	{
		ll p,a,c,b;
		cin>>p>>a>>b>>c;
		ll aa,bb,cc,dd;
		if(p%a==0 || p%b==0 ||p%c==0)
		{
			cout<<0<<endl;
		}
		else
		{
			aa=p/a;
			aa=(aa+1)*a;
			aa=abs(p-aa);

			bb=p/b;
			bb=(bb+1)*b;
			bb=abs(p-bb);

			cc=p/c;
			cc=(cc+1)*c;
			cc=abs(p-cc);

			ll mini=min(aa,bb);
			mini=min(mini,cc);

			cout<<mini<<endl;

  		
		}
		
	}
    
    return 0;
}