Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
n = 100
squareOfSum = sumOfSquares = 0
squareOfSum = 0
# based on a simple internet search
# I found you can find the sum
# of an arithmetic series with
# Sn = n/2(a1 + an)
squareOfSum = n/2 * (1 + n)
squareOfSum = squareOfSum ** 2
#with another internet search
#I found you can get the sum of squares
#with the following
# ((n)(n+1)(2n+1)) / 6
sumOfSquares = (n * (n + 1) * (2 * n + 1)) / 6
#get the difference between the two
difference = squareOfSum - sumOfSquares
print "The square of the sum is %d" % (squareOfSum,)
print "The sum of squares is %d" % (sumOfSquares,)
print "The difference is %d" % (difference,)
#the following code solves it the
#more obvious way but just
#adding up the numbers in a loop
#requires no math prowess, but
#it's slower
squareOfSum = 0
sumOfSquares = 0
i = 1
while i <= n:
sumOfSquares += i**2
squareOfSum += i
i += 1
squareOfSum = squareOfSum ** 2
difference = squareOfSum - sumOfSquares
print "The square of the sum is %d" % (squareOfSum,)
print "The sum of squares is %d" % (sumOfSquares,)
print "The difference is %d" % (difference,)
I decided to do this problem 2 ways. The first method, uses mathematical formulas I found on the web to get the sum of squares and square of the sum. The second method uses a while loop to sum up the squares, and sum up the numbers. I decided to use a while loop, because when I was using a for loop with the range() function, large values of n (100,000,000) caused memory problems because it had to construct the entire list of numbers in memory, For n = 100, both methods are sufficiently fast. However, as you look at larger values of n (100,000,000), the first method starts to show just how much faster it really is.
I think it's also worth mentioning that it's really nice that python doesn't suffer from integer overflows. It just silently keeps on using as many bytes as it needs to represent the numbers and do the math. This can be really useful when dealing with big numbers.