#include<bits/stdc++.h>
using namespace std;
#define il inline
#define rg register
#define int long long
#define M 998244353
const int P=3,Pn=332748118;
il int read()
{
   int re=0,k=1;char ch=getchar();
    while(ch>'9'||ch<'0'){if(ch=='-')k=-1;ch=getchar();}
    while(ch<='9'&&ch>='0'){re=re*10+ch-48;ch=getchar();}
    return re*k;
}
il void write(long long x)
{
    if(x<0)return putchar('-'),write(-x),void();
    if(x<10)return putchar(x+'0'),void();
    return write(x/10),putchar(x%10+'0'),void();
}
signed main()
{
	int T,a,b,c,d;
	T=read();
	while(T--)
	{
		d=read();a=read();b=read();c=read();
		int ans=min((a-d%a)%a,min((b-d%b)%b,(c-d%c)%c));
		write(ans);puts("");
	}
}