Reputation: 123
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.
Upvotes: 5
Views: 8234
Reputation: 762
In Ruby language you can achieve this in this way
def diff_btw_sum_of_squars_and_squar_of_sum(from=1,to=100) # use default values from 1..100.
((1..100).inject(:+)**2) -(1..100).map {|num| num ** 2}.inject(:+)
end
diff_btw_sum_of_squars_and_squar_of_sum #call for above method
Upvotes: 2
Reputation: 32300
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.
Upvotes: 11
Reputation: 1187
# 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 !**
Upvotes: 5
Reputation: 99084
This is a case where it pays to do the math beforehand. You can derive closed-form solutions for both the sum of the squares and the square of the sum. Then the code is trivial (and O(1)).
Need help with the two solutions?
Upvotes: 3
Reputation: 43495
def sum_square_difference(n):
r = range(1,n+1)
sum_of_squares = sum(map(lambda x: x*x, r))
square_sum = sum(r)**2
return sum_of_squares - square_sum
Upvotes: 2