import std.algorithm, std.array, std.bigint, std.conv, std.math, std.stdio, std.typecons, std.range;

long gcd(long a, long b, ref long x, ref long y) {
	if (b == 0) {
        x = 1;
        y = 0;
        return a;
    }
    long d = gcd(b, a % b, y, x); 
    y -= a / b * x;
    return d;
}

long solve(long N, long M) {
	if (M == 0) {
		long p2, p5;
		while (N % 2 == 0) {
			N /= 2;
			p2++;
		}
		while (N % 5 == 0) {
			N /= 5;
			p5++;
		}
		
		return 2L ^^ max(0, 9-p2) * 5L ^^ max(0, 9-p5);
	}

	long x, y;
	auto g = gcd(N, 10L^^9, x, y);
	
	if (M % g != 0) return -1;
	
	x *= -M/g;
	auto mod = 10L^^9 / g;
	if (x < 0) x = x%mod + mod;
	else x = x%mod;
	return x == 0 ? 1 : x;
}

void main() {
	auto t = readln[0 .. $-1].to!uint;
	long[] result;
	foreach (_; 0 .. t) {
		auto tmp = readln.split.to!(long[]);
		result ~= solve(tmp[0], tmp[1] % 10L^^9);
	}
	foreach (r; result) {
		writeln(r);
	}
}