简体   繁体   中英

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

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.

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.

# 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 !**

This is a case where it pays to do the math beforehand. You can derive 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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM