Devise a function to count the sum of a series of integers 1…N, with alternating (+) and (-) operators, using the recursive method

Question:

As per the title, I’ve been given this task to solve. While it is easy to do this using a traditional loop, I am still lost on how this could be achieved using recursion. Any help regarding this will be appreciated!

Here are the expected results:

Input: 4
Output: -2
Explanation: 1 -2 + 3 - 4 = -2

Input 9 
Output: -3
Explanation: 1 - 2 + 3 - 4 + 5 - 6 + 7 - 8 + 9 = 5
Asked By: topinfx

||

Answers:

  1. You have only one parameter n, which is the given input.
  2. You need to keep track of the last number used, and the current sum. This can be done using parameters i and sum respectively.
  3. Odd numbers are added, even are subtracted.

Using the above points, you can derive this simple algorithm:

total(i, n, sum):
    if i is odd -> sum += i
    else -> sum -= i
    if i == n -> return sum
    else -> return total(i+1, n, sum)

answer = total(1, input, 0)
Answered By: Abhinav Mathur

Use following logic

  1. If number is even add
  2. If number is odd subtract

Following is code foe the same

def summation(n, index=2, total=1):
    """
    Summation of alternate (+) and (-) operator
    :param n: Input number for which you need a summation of alternate (+) and (-) operator
    :param index: Last number which was added in summation.
    :param total: Summation of number
    """
    if n == 1:
        return 1
    if index % 2 == 0:
        total += index
    else:
        total -= index
    if index == n:
        return total
    return summation(n, index + 1, total)


print(summation(4)) #It will print output 4
print(summation(9)) #It will print output -3

Answered By: Kasim Sharif
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.