Tuesday, June 22, 2010

Project Euler: Problem 6

http://projecteuler.net/index.php?section=problems&id=6

The sum of the squares of the first ten natural numbers is,
1^(2) + 2^(2) + ... + 10^(2) = 385

The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^(2) = 55^(2) = 3025

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

This one is easy. Brute force--iterating over all values from 1 to n--is a non-starter. It can't scale. Instead, use the equations for mathematical series.

def f1(n):
    # Calculate the sum
    a = n*(n+1)/2

    # Calculate the sum of squares
    b = n*(n+1)*(2*n+1)/6

    # Return the square of sums minus the sum of squares
    return ( a*a - b )

This returns near instantaneously and is independent of n. I.e., it goes as O(1).

No comments:

Post a Comment