UPDATE (Aug 29)
The original blog post had so many typos in it. Sorry. The formula I first posted was n(n-1)/2
which is wrong. It should be n(n+1)/2
.
I had no idea! How come I had to be this old to learn this (despite having a bachelor degree in Mathematics)!
Small series:
>>> 1+2+3+4+5
15
>>> sum(range(5+1))
15
>>> 5*(5+1)//2
15
and larger
>>> 1+2+3+4+5+6+7+8+9+10+11+12+13+14+15
120
>>> sum(range(15+1))
120
>>> 15*(15+1)//2
120
and super large
>>> sum(range(100_000_000+1))
5000000050000000
>>> 100_000_000*(100_000_000+1)//2
5000000050000000
The sum function is O(n) and the multiplication is O(1).
To "prove" that, using speed, you can use:
>>> from time import perf_counter
>>> def T(func):
... t0=perf_counter(); func(); t1=perf_counter(); print((t1-t0)*1000,"ms")
>>> T(lambda: sum(range(100_000_000+1)))
680.1022500148974 ms
>>> T(lambda: 100_000_000*(100_000_000+1)//2)
0.001374981366097927 ms
Comments
There are some problems in your post. Summing the integers between 1 and 5 inclusive is 15, but that's not `sum(range(5))`--it's `sum(range(1, 6))`. There's a similar issue with summing 1 through 15 (and the value of 109 doesn't work at all).
The formula you want is `n*(n+1)//2`.
https://betterexplained.com/articles/techniques-for-adding-the-numbers-1-to-100/