#include<iostream>
#include<cstring>
#include<cstdio>

using namespace std;

int t;

int main() {
	scanf("%d",&t);
	for(int i = 1;i <= t; i++) {
		long long p,a,b,c,a1,b1,c1,ans = 8000000000000000000;
		scanf("%lld%lld%lld%lld",&p,&a,&b,&c);
		a1 = p / a;
		b1 = p / b;
		c1 = p / c;
		if(p % a == 0) ans = min(ans,p % a);
		else ans = min(ans,a - p % a);
		if(p % b == 0) ans = min(ans,p % b);
		else ans = min(ans,b - p % b);
		if(p % c == 0) ans = min(ans,p % c);
		else ans = min(ans,c - p % c);
		printf("%lld\n",ans);
	}
	
	
	
	return 0;
} 
