‘N’ people are standing in a circle numbered from ‘1’ to ‘N’ in clockwise order. First, the person numbered 1 will proceed in a clockwise direction and will skip K-1 persons including itself and will kill a Kth person. Now (K+1)th person from 1 will start and will kill the Kth person from itself.
You have to find the position of the last person surviving with respect to initial numbering.
Note:A person can also kill himself.
The first line of input contains an integer ‘T’ denoting the number of test cases.
The first and only line of each test case contains two integers ‘N’ and ‘K’. Where ‘N’ is the total no of persons standing around circle and ‘K’ number indicates kth person is killed.
Output Format
For each test case, return a single integer denoting the position of the last person surviving.
Note:
You are not required to print the output explicitly, it has already been taken care of. Just implement the function.
Constraints
1 <= ’T’ <= 50
1 <= ’N’,’K’ <= 10^4
Time Limit: 1 sec
2
4 2
7 3
1
4
Explanation :-
For the first TestCase:-



The position of the last person is 1.Hence ans is 1.
For the second case:-
The first starting point is 1 and 3 is killed.
The starting point is 4 and 6 is killed.
The starting point is 7 and 2 is killed.
The starting point is 4 and 7 is killed.
The starting point is 1 and 1 is killed.
2
5 6
3 6
4
1
Use Brute Force approach.
Approach:- The key id is to store all positions of a person in vector and remove all kth position from starting point in vector. After removing an element from the vector starting point is also changed.
Algorithm:
O(N^2), where ‘N’ is the number of persons.
We iterate every index in worse case in each iteration we delete element from the array which takes O(N) time. Hence time complexity is O(N^2).
O(N), where ‘N’ is the number of persons.
Create an index array to store the positions of all persons.