// Created by XIRHXQ on 03/05/21.
#include<bits/stdc++.h>

typedef long long ll;
using namespace std;

#define maxn 101010
#define mod 1000000007

int main() {
    int T;
    scanf("%d", &T);
    while (T--) {
        ll p,a,b,c;
        cin>>p>>a>>b>>c;
        cout<<min(min((a-p%a)%a,(b-p%b)%b),(c-p%c)%c)<<endl;
    }
    return 0;
}

