---
title: "No.6 The difference between the sum of the squares and the square of the sum"
author: "诗意的栖居"
date: "2012-08-22T09:52:33Z"
tags: []
categories: ["编程语言"]
slug: "no-6-the-difference-between-the-sum-of-the-squares-and-the-square-of-the-sum"
draft: false
lastmod: "2012-08-23T10:16:53Z"
id: 1652181
url: "https://fyan.iteye.com/blog/1652181"
---

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()

problem(range(1,101))

t4 = time.time()
print "time:%s"  %str(t4-t3)