#include <bits/stdc++.h>
using namespace std;
const long long inf = 2e18;
int main(){
    cin.tie(NULL);
    ios_base::sync_with_stdio(false);
    int t; cin >> t;
    while(t--){
        long long a, b, c, p; cin >> p >> a >> b >> c;
        long long ans = inf;
        ans = min((a - p % (a))%a, min( (b-p % (b))%b, (c-p % (c))%c));
        cout << ans << "\n";
    }
    return 0;
}
