Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

sum

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.

like image 513
Kuma Avatar asked Mar 23 '13 23:03

Kuma


Video Answer


2 Answers

The function can be written with pure math like this:

The formula

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.

like image 110
Volatility Avatar answered Oct 30 '22 10:10

Volatility


# As beta says, # (sum(i))^2 - (sum(i^2)) is very easy to calculate :) # A = sum(i) = i*(i+1)/2 # B = sum(i^2) = i*(i+1)*(2*i + 1)/6 # A^2 - B = i(i+1)(3(i^2) - i - 2) / 12 # :) # no loops... just a formula !**

like image 36
mlwn Avatar answered Oct 30 '22 10:10

mlwn