Source code available on GitHub.
Here’s the problem:
Well, the question looks long but I think this is actually the simplest problem we’ve had yet. The sum of all integers from to is
It’s not hard to see why. In fact, there’s a brilliant story about how the young Gauss found this trick when an annoyed teacher gave him this problem to keep him occupied, expecting it to take him a long time to manually sum all the numbers.
Let this sum be , so that
We write the sum backwards as
and add the two equations term-by-term, getting
It’s easy to see that this is lots of and so . Divide by two, and we have just as we were hoping for.
A quick implementation of this as a function is:
def sumofintegers(n): return n*(n+1)/2
A very similar result for the sum of squares takes a just a little more effort to show, but I won’t prove it here:
A similar Python function would be:
def sumofsquares(n): return n*(n+1)*(2*n+1)/6
So, all we need to do is take the difference of the sum of squares and the square of the regular sum, up to
n. We’re done!
def sumofsquares(n): return n*(n+1)*(2*n+1)/6 def sumofintegers(n): return n*(n+1)/2 def specialdifference(n): # Finds the difference between the sum of squares and the square sum up to n return abs(sumofsquares(n) - (sumofintegers(n))**2) print(specialdifference(100))