Instead of using a while loop to subtract K from N until N is less than K, we can use the modulus operator (%). This operator returns the remainder of the division of the number before it by the number after it. This will give us the same result as your while loop, but in O(1)

Here’s your optimized code:

T = int(input())
for _ in range(T):
N, K = map(int, input().split())
if(K == 0):
print(N)
else:
print(N % K)