#include<bits/stdc++.h>
#define int long long
using namespace std;
int cal(int t1,int t2){
	return (t1+t2-1)/t2*t2-t1;
}
signed main(){
	int t;
	cin>>t;
	while(t--){
		int p,a,b,c;
		cin>>p>>a>>b>>c;
		cout<<min(cal(p,a),min(cal(p,b),cal(p,c)))<<"\n";
	}
	return 0;
}