#!/usr/bin/env python # coding: utf-8 # We know that the formula for the [sum of squares](https://en.wikipedia.org/wiki/Square_pyramidal_number) is $\sum_{k=1}^{n} k^2 = \frac{2n^3 + 3n^2 + n}{6}$ and that $\sum_{k=1}^{n} k = \frac{n*(n+1)}{2}$ (see [Arithmetic progression](https://en.wikipedia.org/wiki/Arithmetic_progression)). So we simply need to do $\sum_{k=1}^{n}k^2 - (\sum_{k=1}^{n}k)^2 = \frac{3n^4 + 2n^3 - 3n^2 - 2n}{12}$ # In[1]: def equation(n): return (3*n**4 + 2*n**3 - 3*n**2 - 2*n) // 12 equation(100) # In[ ]: