its a past problem from RE contest. its editorial is available search for it.

Hope this help!

```
from math import ceil
for _ in range(int(input())):
n,k=map(int,input().split())
# if n==0 , it is found after 0,2,6,12,20,......
if(n==0):
p=k-1
total=p*(p+1)
else:
# otherwise break the sequence like
# 01 0121 012321 01234321 .....
# you can see that length of n have the max element n//2
m=n*2
#so if for eg we want n=3 at k=2
# we find where it first occured using n*2
#and then we can see except the first occurrence
#later grouped sequence contain two occurences
# so we find in which group the elemnt present
m=m+(k//2)*2
# no we check how many groups are left behind the current one
c=(m//2)-1
# now if k is even then it present in start else in the end
if(k%2==0):
#if element at start answer will be
# elemnt + sum of elements in previous gorups
total=n+((c)*(c+1))
else:
# if element at end answer will be
# total lenth of gorup - element + sum of elements in previous gorups
total=(m-n)+((c)*(c+1))
print(total)
```