#include<stdio.h>

int main(){
   long long int t,i,j,a,b,c,p;
    scanf("%lld",&t);
    for(i=0;i<t;i++){
        scanf("%lld%lld%lld%lld",&p,&a,&b,&c);
    
long long    int arr[3],min=999999999999999999;
    arr[0]=a-p%a;arr[1]=b-p%b;arr[2]=c-p%c;
    if(arr[0]==a||arr[1]==b||arr[2]==c){
        printf("0\n");continue;
    }
    for(j=0;j<3;j++){
        if(arr[j]<min){
            min=arr[j];
        }
    }
    printf("%lld\n",min);
}return 0;
}        
    