#include<bits/stdc++.h>
#define endl "\n"
using namespace std;
typedef long long ll;
typedef unsigned long long ull;

const int N = 1e6;

int n;

int arr[N + 10];

int check(int cap)
{


    for(int i=0; i<n; i++)
    {



    }

    //return cnt;
}

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

    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);

    /*int t, k = 1;

    cin >> t;

    while(t--)
    {
        int  m;

        cin >> n >> m;


        for(int i=0; i<n; i++)
        {
            cin >> arr[i];
        }

        cout << check(6) << endl;

        /*int l = 1, r = 1e7, mid, res = 0;

        while(l<=r)
        {
            mid = l + (r - l) / 2;

            int res = check(mid);

            if(res >= m)
            {
                r = mid - 1;
                res = mid;
            }

            else
            {
                l = mid + 1;
            }

        }


        cout << "Case " << k++ << ": " << res << endl;


    }*/

    int t;

    cin >> t;

    while(t--)
    {
        ll p, a, b, c;

        cin >> p >> a >> b >> c;

        ll z1 = ceil(p/(double)a);

        ll res1 = abs((z1*a) - p);

        ll z2 = ceil(p/(double)b);

        ll res2 = abs((z2*b) - p);

        ll z3 = ceil(p/(double)c);

        ll res3 = abs((z3*c) - p);

        cout << min(res1, min(res2, res3)) << endl;

        //cout << res1 << " " << res2 << " " << res3 << endl;
        //printf("%.0lf\n", min(res1, min(res2, res3)));
    }










}
