#include <iostream>
using namespace std;
int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int t;
    cin>>t;
    while(t--){
        long long p, a, b, c;
        cin>>p>>a>>b>>c;
        long long pa = (p/a + !!(p%a))*(a);
        long long pb = (p/b + !!(p%b))*(b);
        long long pc = (p/c + !!(p%c))*(c);
        if((pa <= pb) && (pa <= pc)){
            cout<<pa - p<<'\n';
        }else if((pb <= pa) && (pb <= pc)){
            cout<<pb - p<<'\n';
        }else cout<<pc - p<<'\n';
    }
    return 0;
}
