```
#include<bits/stdc++.h>
#define int long long
using namespace std;
int T;
signed main()
{
cin>>T;
while(T--)
{
int p,a,c,ans=5e18;
cin>>p;
for(int i=1;i<=3;i++)
{
cin>>a;
if(p<=a)
ans=min(ans,a-p);
else
{
c=p/a;
if(p%a!=0)
c++;
ans=min(ans,1ll*a*c-p);
}
}
cout<<ans<<endl;
}
return 0;
}
```