
#include<bits/stdc++.h>

using namespace std;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int t;
    cin>>t;

    while(t--)
    {
        long long p,a,b,c;
        cin>>p>>a>>b>>c;

        long long ansa = p % a ? a * (( p / a) + 1) - p : 0;
        long long ansb = p % b ? b * (( p / b) + 1) - p : 0;
        long long ansc = p % c ? c * (( p / c) + 1) - p : 0;

        //cout<<ansa<<" "<<ansb<<" "<<ansc<<endl;

        cout<<min(ansa,min(ansb,ansc))<<endl;
    }   

    return 0;
}