#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;

int main() {
	ll t;
	cin >> t;
	while(t--){
	ll p,a,b,c;cin>>p>>a>>b>>c;
        ll aa,bb,cc;
        if(p>a)
        {
            ll rem = (p+a)%a;
            if(rem==0)
                aa=0;
            else
            {
                aa=(a+p-rem);
                aa=abs(p-aa);
            }
        }else{
            aa=a-p;
        }
        if(p>b)
        {
            ll rem = (p+b)%b;
            if(rem==0)
                bb=0;
            else
            {
                bb=(b+p-rem);
                bb=abs(bb-p);
            }
        }else{
            bb=b-p;
        }
        if(p>c)
        {
            ll rem = (p+c)%c;
            if(rem==0)
                cc=0;
            else
            {
                cc=(c+p-rem);
                cc=abs(p-cc);
            }
        }else{
            cc=c-p;
        }
        cout<<min(aa,min(bb,cc))<<endl;
    }
}
