#include<bits/stdc++.h>
#define int long long
using namespace std;

int t,p,a,b,c;
signed main(){
	cin>>t;
	while (t--){
		cin>>p>>a>>b>>c;
		a=(a-p%a)%a;
		b=(b-p%b)%b;
		c=(c-p%c)%c;
		cout<<min({a,b,c})<<'\n';
	}
	return 0;
}
