#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);

	#ifndef ONLINE_JUDGE
	freopen("input.txt","r",stdin);
	freopen("output.txt","w",stdout);
	#endif

	int t;
	cin>>t;
	while(t--)
	{
		ll p,a,b,c;
		cin>>p>>a>>b>>c;
		ll t1=p/a*a,t2=p/b*b,t3=p/c*c;
		if(t1<p)t1+=a;
		if(t2<p)t2+=b;
		if(t3<p)t3+=c;
		cout<<min({t1-p,t2-p,t3-p})<<endl;
		

		
	}


	return 0;
}