No.6 The difference between the sum of the squares and the square of the sum

Q:
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 = 552 = 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.

A:
import time

t1 = time.time()
''' method 1
    fast than method 2
'''
sumone = 0
sumtwo = 0

for i in range(1,101):
    sumone += i ** 2
    sumtwo += i

sumtwo = sumtwo ** 2

print sumtwo - sumone
t2 = time.time()
print "time:%s" %str(t2-t1)

''' method 2
    多出来的项目是2((a*1 + a*2 + a*3 + ... +a*(a-1)) + (b*1 + b*2 + b*3 + ... +b*(b-1) + ... )
'''
sumthree = 0
for i in range(100,1,-1):
    for j in range(1,i):
        sumthree += i * j

print sumthree * 2
t3 = time.time()
print "time:%s" %str(t3-t2)

''' method 3
    faster than the two above
'''

def problem(r):
    return sum(r) ** 2 - sum([x**2 for x in r])

problem(range(1,101))

t4 = time.time()
print "time:%s"  %str(t4-t3)

你可能感兴趣的:(diff)