Python program: Sum of the first n numbers
Add up 1 + 2 + … + n, with a loop and with the formula.
The code
n = 100 total = 0 for i in range(1, n + 1): total += i print("loop: ", total) print("sum(): ", sum(range(1, n + 1))) print("formula:", n * (n + 1) // 2)
Output
loop: 5050 sum(): 5050 formula: 5050
How it works
An accumulator adds each number. sum(range(…)) does the same; the formula n(n+1)/2 (found by Gauss as a schoolboy) needs no loop at all.
Python features used
Learn the ideas behind it in the free lesson Loops.