Efficient summation in Python
The fastest way to compute sum in Python
result = ((((12 * n + 45) * n + 50) * n + 15) * n - 2) * n // 120
How I got there:
- Rewrite the inner sum as the well-known
x*(x+1)//2
. So the whole thing becomessum(x**2 * x*(x+1)//2 for x in range(n+1))
. - Rewrite to
sum(x**4 + x**3 for x in range(n+1)) // 2
. - Look up formulas for
sum(x**4)
andsum(x**3)
. - Simplify the resulting mess to
(12*n**5 + 45*n**4 + 50*n**3 + 15*n**2 - 2*n) //
…