Function to calculate the difference between sum of squares and square of sums

python, sum

Solution

The function can be written with pure math like this:

Translated into Python:

def square_sum_difference(n):
    return int((3*n**2 + 2*n) * (1 - n**2) / 12)

The formula is a simplification of two other formulas:

def square_sum_difference(n):
    return int(n*(n+1)*(2*n+1)/6 - (n*(n+1)/2)**2)

`n*(n+1)*(2*n+1)/6` is the formula described here, which returns the sum of the squares of the first `n` natural numbers.

`(n*(n+1)/2))**2` uses the triangle number formula, which is the sum of the first `n` natural numbers, and which is then squared.

This can also be done with the built in `sum` function. Here it is:

def sum_square_difference(n):
    r = range(1, n+1)  # first n natural numbers
    return sum(i**2 for i in r) - sum(r)**2

The `range(1, n+1)` produces an iterator of the first `n` natural numbers.

>>> list(range(1, 4+1))
[1, 2, 3, 4]

`sum(i**2 for i in r)` returns the sum of the squares of the numbers in r, and `sum(r)**2` returns the square of the sum of the numbers in r.

Problem

I am trying to Write a function called `sum_square_difference` which takes a number n and returns the difference between the sum of the squares of the first n natural numbers and the square of their sum. I think i know how to write a function that defines the sum of squares ``` def sum_of_squares(numbers): total = 0 for num in numbers: total += (num ** 2) return(total) ``` I have tried to implement a square of sums function: ``` def square_sum(numbers): total = 0 for each in range: total = total + each return total**2 ``` I don't know how to combine functions to tell the difference and i don't know if my functions are correct. Any suggestions please? I am using Python 3.3 Thank you.

Original source