You have given two positive integers N and K. Your task is to print a series of numbers i.e subtract K from N until it becomes 0 or negative then add K until it becomes N. You need to do this task without using any loop.
For Example:For N = 5 , K = 2
Series = [ 5, 3, 1, -1, 1, 3, 5]
The first line of input contains a single integer T, representing the number of test cases or queries to be run
The first line of each test contains two space-separated integers N and K.
Output format :
For each test case, print a single line containing the required series.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 100
1 <= N <= 3000
1 <= K <= N
Time Limit: 1sec
2
3 2
5 4
3 1 -1 1 3
5 1 -3 1 5
For the 1st test case:
The numbers in the sequence are 3, 3 - 2, 3 - 2 - 2, 3 - 2 - 2 + 2, 3 - 2 - 2 + 2 + 2, which is the same as 3, 1, -1, 1, 3.
For the 2nd test case:
The numbers in the sequence are 5, 5 - 4, 5 - 4 - 4, 5 - 4 - 4 + 4, 5 - 4 - 4 + 4 + 4, which is the same as 5, 1, -3, 1, 5.
1
4 2
4 2 0 2 4
Think of a solution using recursion.
The idea here is to use recursion,we can print current N two times in the current recursion stack. One for decreasing order and one for increasing order.
Steps :
void series(answer, N, K):
O(N), where N is the given number.
In the worst case when K = 1 we need to recur for O(N) times. Hence the overall complexity will be O(N).
O(N), where N is the given number.
In the worst case, when K = 1 we need O(N) recursion calls. Hence the overall complexity will be O(N).