Summation formula
We learned in Problem 1: Multiples of 3 and 5 that:
∑k=n(n+1)2
This gives the following formula for the square of the sum:
(1+2+...+10)2=(∑k)2=(n(n+1)2)2=n2(n+1)24
The sum of the squares can be found using the formula:
∑k2=n(n+1)(2n+1)6
There are many demonstrations to prove this equation, let's just look at one of them:
(k−1)3=k3−3k2+3k−1k3−(k−1)3=3k2−3k+1n∑k=1(k3−(k−1)3)=n∑k=13k2−3k+1n∑k=1k3−n∑k=1(k−1)3=3n∑k=1k2−3n∑k=1k+n∑k=11n∑k=1k3−n−1∑k=0k3=3n∑k=1k2−3n(n+1)2+nn3=3n∑k=1k2−3n(n+1)2+nn∑k=1k2=13n3+n(n+1)2−13nn∑k=1k2=n(n+1)(2n+1)6
The solution can be found in constant time with these two equations:
n2(n+1)24−n(n+1)(2n+1)6=3n4+2n3−3n2−2n12
From solution2.py:
def sum_square_difference(n=100):
return (3 * n**4 + 2 * n**3 - 3 * n**2 - 2 * n) // 12