#include<bits/stdc++.h>

using namespace std;

int main()
{
    int t;
    cin >> t;
    while(t--)
    {
        long long x,p,q,r,a,b,c,ans=LLONG_MAX;
        cin >> x >> p >> q >> r;
        a=p,b=q,c=r;

        if(p>=x)
        {
            ans=min(ans,p-x);
        }
        else
            ans=min(ans,((x/p+!(x%p==0))*p-x));

        if(q>=x)
        {
            ans=min(ans,q-x);
        }
        else
        {
            ans=min(ans,((x/q+!(x%q==0))*q-x));
        }

        if(r>=x)
        {
        ans=min(ans,r-x);
        }
        else
        {
            ans=min(ans,((x/r+!(x%r==0))*r-x));

        }

        cout<<ans<<endl;

    }
}
