#include <bits/stdc++.h>
using namespace std;

#define LL long long
#define RI register int
#define pr(x) cout<<#x<<" = "<<x<<endl
#define p(x) cout<<x<<endl
#define pr2(x,y) cout<<#x<<"["<<y<<"] = "<< x [ y ] <<endl
#define SP <<"   "<<

LL f(LL a,LL p)
{
	return a - (p+a-1)%a -1;
}

int main()
{
	int T;
	cin>>T;
	while(T--)
	{
		LL p,a,b,c;
		cin>>p>>a>>b>>c;
		LL t;		
		t=min(f(a,p),f(b,p));
		t=min(t,f(c,p));
		p(t);
	}
}