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

void solve() {
	long long int p, a, b, c;
	cin >> p >> a >> b >> c;
	long long int aa = (a-(p%a))%a;
	long long int bb = (b-(p%b))%b;
	long long int cc = (c-(p%c))%c;
	cout << min(aa,min(bb,cc)) << endl;
}


int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout << fixed;
	int tc;
	cin >>tc;
	for(int ts = 0; ts<tc; ts++) {
		solve();
	}
	
	return 0;
} 
