You have given a series, 1+2+3-4-5-6+7+8+9-10-11-12+......N . Your task to print the sum of the Nth element.
Sample Input 1 10 Sample Output 1 5 Sample Input 2 20 Sample Output 2 12 Explanation of Sample Input 2: 1+2+3-4-5-6+7+8+9-10-11-12+13+14+15-16-17-18+19+20 = 12. Sum up to the 20th of this series.We can write a function to compute the sum of the series up to the Nth element. The function can be implemented as follows:
def sum_series(N):
sum = 0
for i in range(1, N+1):
if i % 3 == 0:
sum -= i
else:
sum += i
return sum
This function starts a loop from 1 to N+1 (since range is not inclusive of the last element), and for each number in the loop, it checks if the number is divisible by 3. If it is, it subtracts the number from the sum. If it isn't, it adds the number to the sum.
For example, for N=10, the function will sum the series 1+2+3-4-5-6+7+8+9-10 and return 5. For N=20, the function will sum the series 1+2+3-4-5-6+7+8+9-10-11-12+13+14+15-16-17-18+19+20 and return 12.
To use the function, you can call sum_series(N)
, where N is the number of elements in the series that you want to sum up to.
0 Comments