Last Updated: 7 Jan, 2021

Print Series

Easy
Asked in companies
EcomExpressIndus Valley PartnersMAQ Software

Problem statement

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]
Input format :
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.
Constraints :
1 <= T <= 100   
1 <= N <= 3000 
1 <= K <= N 

Time Limit: 1sec

Approaches

01 Approach

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 : 

 

  • Declare an empty array to store our series, say answer.
  • Define and call function series(answer, N, K), where N, and K is the given number.
  • At last return answer.

 

void series(answer, N, K):

 

  • Add N to answer.
  • Base condition, if N equals to 0 or negative then return.
  • Recur for series(answer, N - K, K).
  • Add N to answer.