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: 4
Explanation: 1 2 - 3 4 = 4
Input 9
Output: -3
Explanation: 1 2 - 3 4 - 5 6 - 7 8 - 9 = -3
CodePudding user response:
- You have only one parameter
n
, which is the given input. - You need to keep track of the last number used, and the current sum. This can be done using parameters
i
andsum
respectively. - 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)
CodePudding user response:
Use following logic
- If number is even add
- 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