Problem 139489 · easy · Level 01 Prerequisites & Setup

Alternating Plus and Minus

loops · range · modulo · accumulation

Write alternating_sum(n) that returns 1 - 2 + 3 - 4 + 5 - ... continuing up to n. Odd numbers are added and even numbers are subtracted. For n = 0 return 0.

Examples

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

Input:  n = 4
Output: -2

Constraints

  • 0 <= n <= 10**5

Goals

  • Alternate between two actions inside a loop
  • Use the parity of the loop counter
Starting Python…