
// Problem: A. Three swimmers
// Contest: Codeforces - Codeforces Round #704 (Div. 2)
// URL: https://codeforces.com/problemset/problem/1492/A
// Memory Limit: 512 MB
// Time Limit: 1000 ms
// Powered by CP Editor (https://github.com/cpeditor/cpeditor)

#include<bits/stdc++.h>
typedef long long ll ;
#define int ll 
using namespace std ;
signed main( )
{
    ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    int t;
    cin>>t;
    while(t--)
    {
        int p,a,b,c ;
        cin >>p>>a>>b>>c;
        int s1= (p+a-1)/a;
        int s2= (p+b-1)/b;
        int s3= (p+c-1)/c;
        int x= s1*a-p;
        int y= s2*b-p;
        int z= s3*c-p;
        cout<<min(x,min(y,z));
        cout<<endl;
    }
    
    return 0 ;
}    