frac = [[0] * 1000 for _ in range(1000)] for k in range(1, 1000): for x in range(k): f = (x * 1000 // k) % 1000 frac[f][k] += 1 for f in range(1000): for k in range(1, 1000): frac[f][k] += frac[f][k-1] def solve(): n, s = input().split() n = int(n) f = int(s[-3:]) return frac[f][min(n, 999)] + max(n - 999, 0) t = int(input()) for _ in range(t): print(solve())