#include<bits/stdc++.h>
using namespace std;

int main() {
    int t;cin>>t;
    while(t--){
        
        long long int p,a,b,c,a1,a2,a3;
        cin>>p>>a>>b>>c;
        a1=a-(p%a);
        if(a1==a)a1=0;
        a2=b-(p%b);
        if(a2==b)a2=0;
        a3=c-(p%c);
        if(a3==c)a3=0;
        cout<<min(a1,min(a2,a3))<<'\n';
    }
}