#include <iostream>

long long wait_time(long long p, long long a, long long b, long long c)
{
    long long wait_a = a + a * (p / a) - p;
    long long wait_b = b + b * (p / b) - p;
    long long wait_c = c + c * (p / c) - p;

    if(wait_a == a) wait_a = 0;
    if(wait_b == b) wait_b = 0;
    if(wait_c == c) wait_c = 0;

    return std::min(std::min(wait_a, wait_b), wait_c);
}

int main()
{
    int t;
    std::cin >> t;

    for(int i = 0; i < t; ++i)
    {
        long long p, a, b, c;
        std::cin >> p >> a >> b >> c;

        std::cout << wait_time(p, a, b, c) << "\n";
    }

    return 0;
}