#include<bits/stdc++.h>
using namespace std;
int main(){
	int t;
	cin>>t;
	while(t){
		t--;
		long long int p,a,b,c;
		cin>>p>>a>>b>>c;
		long long int a1=p%a;
		if(a1!=0)
		a1=a-a1;
		long long int b1=p%b;
		if(b1!=0)
		b1=b-b1;
		long long int c1=p%c;
		if(c1!=0)
		c1=c-c1;
		a1=min(a1,min(b1,c1));
		cout<<a1<<endl;
	}
}