// Omar_Elaraby
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define EPS 1e-9

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0), cout.tie(0);
//	freopen("in.txt", "r", stdin);
//	freopen("out.txt", "w", stdout);

	int tt;
	cin >> tt;
	while (tt--) {
		long long p;
		vector<ll> v(3);
		cin >> p;
		for (ll &i : v) {
			cin >> i;
		}

		long long ans = LLONG_MAX;
		for (int i = 0; i < 3; ++i) {
			if (v[i] >= p) ans = min(ans, v[i] - p);
			else ans = min(ans, v[i] * ((p + v[i] - 1) / v[i]) - p);
		}
		cout << ans << '\n';
	}

	return 0;
}

