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

Anonymous

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`.

Your email will never ever be published.

Previous:
Find GitHub Pull Request by commit SHA August 21, 2025 GitHub
Next:
gg commit with suggested --no-verify August 29, 2025 Bun
Related by category:
In Python, you have to specify the type and not rely on inference October 10, 2025 Python
A Python dict that can report which keys you did not use June 12, 2025 Python
Native connection pooling in Django 5 with PostgreSQL June 25, 2025 Python
Combining Django signals with in-memory LRU cache August 9, 2025 Python