
		#include <bits/stdc++.h>
		using namespace std;
		
		int main()
		{
			int t; cin>>t;
			
			while(t--){
				long long int p,arr[3],mul[3]; cin>>p>>arr[0]>>arr[1]>>arr[2];
					long long int min=0;
					for(int i=0; i<3; i++){
						if(p%arr[i]==0){
							mul[i] = p/arr[i];
						}else{
							float x;
							x =  (p/arr[i]);
							mul[i] = (trunc(x*10)/10)+1;
						}
						if(i==0){
							min = ((mul[i]*arr[i])-p);
						}else{
							long long int x =  ((mul[i]*arr[i])-p);
							if(x<min)min = x;
						}
						//cout<<((mul[i]*arr[i]))<<" ";
					}
					cout<<min<<"\n";	
			}	
		}