Problem 138006 · easy · Level 01 Prerequisites & Setup

Sum of the First N Numbers

loops · range · accumulation

Write a function sum_to_n(n) that returns 1 + 2 + 3 + ... + n using a loop. When n is 0 there is nothing to add, so return 0.

In maths notation this is \sum_{i=1}^{n} i. To check your answer, compare it with Gauss's formula \frac{n(n+1)}{2}: for n = 4 that is \frac{4 \cdot 5}{2} = 10.

Examples

Input:  n = 4
Output: 10
Explanation: 1 + 2 + 3 + 4 = 10

Input:  n = 0
Output: 0

Constraints

  • 0 <= n <= 10**5

Goals

  • Use a for loop with range() to visit every number from 1 to n
  • Keep a running total in a variable
Starting Python…