Efficient summation in Python

result = ((((12 * n + 45) * n + 50) * n + 15) * n - 2) * n // 120

How I got there:

  1. Rewrite the inner sum as the well-known x*(x+1)//2. So the whole thing becomes sum(x**2 * x*(x+1)//2 for x in range(n+1)).
  2. Rewrite to sum(x**4 + x**3 for x in range(n+1)) // 2.
  3. Look up formulas for sum(x**4) and sum(x**3).
  4. Simplify the resulting mess to (12*n**5 + 45*n**4 + 50*n**3 + 15*n**2 - 2*n) //

--

--

--

Flutter and Native Android developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Non-trivial interview with Natallia Shauchenka

Natallia Shauchenka (Senior Product Manager @ BCG Digital Ventures)

Installing LAMP on Ubuntu

Refactoring #3: Optimizing Eloquent queries & console commands

Python Environment Setting:

6 Most Popular Bug Tracking Tools

Counting at compile time

CS371g Summer 2020: Yuhan Zheng

Getting a folders size the easy way

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Flutter Developer

Flutter Developer

Flutter and Native Android developer

More from Medium

Powershell Scripting Guide to Python

Virtual environment Setup for python project

Connect to Oracle Autonomous Database from Python without using the Instance Wallet

A Ready Reckoner To Upgrade From Python 2 to Python 3