ITeye博客

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

诗意的栖居 · 2012-08-22 09:52 · 算法 · 编程语言 · Markdown

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((a1 + a2 + a3 + ... +a(a-1)) + (b1 + b2 + b3 + ... +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()

problem(range(1,101))

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

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。