‘Tis the season for a holiday tune, and what better classic is there than The Twelve Days of Christmas?
And how lucky the narrator is to have such a thoughtful true love, no?
So many gifts!
Twelve drummers, eleven pipers, …
For a total of 78 gifts!
Since as we all know1:
12+11+...+1=i=1∑Ni=2N(N+1)
As a quick aside, we can observe the above is true via some rearranging:
Ok, so anyway, what an impressive Christmas haul!
But wait… if you listen to the lyrics literally, is that right?
On the first day of Christmas, my true love gave to me: A partridge in a pear tree. On the second day of Christmas, my true love gave to me: Two turtle doves, and a partridge in a pear tree. …
This sugar daddy is handing out a new partridge each day! This means the total number of gifts is actually more like:
1+(1+2)+(1+2+3)+...=i=1∑Nj=i∑ij
Now, if we wanted to compute the total, it would be straightforward do it with something like this:
N =12sum(sum(j for j in range(1, i +1)) for i in range(1, N +1))
# 364
(incidentally, one for every day of the year except one!) but where’s the fun in that?!
We need a closed-form solution, in case we have, you know, some future Christmas season with 1e10 days or whatever (good luck with that quadratic loop then!).
So, it’s conveneient to write the above as a triangular matrix, where rows are days, and columns are gifts:
111⋮022003…⋱
And we want the sum of the whole thing. Now, looking down columns rather than across rows, it becomes clear that the sum can be written like:
From the previous section, we know the sum of the first N integers, but what about the sum of their squares?
Well, this gets a little tricky.
Suppose we consider the following expression (which, I shamelessly stole from Stack Overflow):