#include <bits/stdc++.h>
using namespace std;
#define ll long long 
int main()
{
    int t;
    cin>>t;
    for(int i=0;i<t;i++)
    {
        ll a,b,c,d;
        cin>>a>>b>>c>>d;
        ll v = b,m = c, f = d;
        ll w = a%b;
        ll e = a%c;
        ll r = a%d;
        b = a/b;
        c = a/c;
        d = a/d;
        if(w)
        {
            b++;
        }
        if(e)
        {
            c++;
        }
        if(r)
        {
            d++;
        }
        cout<<min({b*v-a,c*m-a,f*d-a})<<"\n";
    }
    return 0;
}