def extgcd(a, b): """ 拡張ユークリッド互除法 ax + by = gcd(a,b) の最小整数解 (gcd(a,b), x, y) を返す Args: a (int): b (int): Returns: Tuple[int, int, int] """ u = y = 1 v = x = 0 while a: q = b // a x, u = u, x-q*u y, v = v, y-q*v b, a = a, b-q*a return b, x, y mod = 10**9 + 7 for _ in range(int(input())): x, k = map(int, input().split()) # k * x' - (mod - 1) * y' = 1 _, b, _ = extgcd(k, -mod + 1) print(pow(x, b, mod))