#include<iostream> 
using namespace std;
#define ll long long
ll int min(ll int a,ll int b,ll int c){
    if(a<=b && a<=c) return a;
    if(b<=a &&  b<=c) return b;
    return c;
}
int main(){
    
  ll int t;
  cin>>t;
  while(t--) {
      ll int p,a,b,c;
      cin>>p>>a>>b>>c;
      ll int a1,b1,c1;
      if(p<=a) {
          a1=a-p;
      }
      if(p>a){
        a1=p%a;
        if(a1!=0)
          a1=a-a1;
      }
      if(p<=b) {
          b1=b-p;
      }
      if(p>b){
        b1=p%b;
        if(b1!=0)
          b1=b-b1;
      }
      if(p<=c) {
          c1=c-p;
      }
      if(p>c){
        c1=p%c;
        if(c1!=0)
          c1=c-c1;
      }

      // else{
      //     a1=p%a;
      //     if(a1!=0)
      //       a1=a-a1;
      //     b1= p%b;
      //     if(b1!=0)
      //      b =b-b1;
      //     c1=p%c;
      //     if(c1!=0)
      //     c1=c-c1;
      // }
      
      cout<<min(a1,b1,c1)<<endl;
      }
      return 0;
}