[Project Euler] 来做欧拉项目练习题吧: 题目006

                                              [Project Euler] 来做欧拉项目练习题吧: 题目006

                                                               周银辉

 

问题描述:

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. 

 

问题分析:

嗯,这是个纯数学题了,有数学公式的:

(1+2+3...+n)^2 = ((1+n)*n/2)^2

(1^2 + 2^2 + 3^2 +...+ n^2) = 1/6 * n(n+1)(2n+1) 

 

1+2+3+...+n这是等差数列,所以(1+n)*n/2

而(1^2 + 2^2 + 3^2 +...+ n^2) 嘛,可以这样推导:

首先,

     n*(n+1)*(2n+1) - (n-1)*n*(2n-1)

=  (n^2+n)*(2n+1) - (n^2-n)*(2n-1)

=  (2*n^3+n^2+2*n^2+n) - (2*n^3-n^2-2*n^2+n) 

=  2*n^3+3n^2+n - 2*n^3+3*n^2-n

=  6*n^2

然后,
当 n=1时, 1*2*3 - 0         = 6*1^2
当 n=2时, 2*3*5 - 1*2*3 = 6*2^2
当 n=3时, 3*4*7 - 2*3*5 = 6*3^2
...
当 n=n-1时,(n-1)*n*(2n-1) - (n-2)*(n-1)*(2n-3) = 6*(n-1)^2
当 n=n时,   n*(n+1)*(2n+1) - (n-1)*n*(2n-1)     = 6*n^2
上面的各个等式左右对应相加,左边的很多项会正负抵消,然后得到:
n*(n+1)*(2n+1) = 6*(1^2+2^2+3^2+...+n^2)

 所以,(1^2+2^2+3^2+...+n^2) = n(n+1)(2n+1)/6 

 

注:当完成题目后,对于某些题,官方网站会给出参考答案,在我的博客里不会将官方答案贴出来,仅仅会写下我自己当时的思路,除非两者不谋而合。另外,如果你有更好的思路,请留言告诉我,我非常乐意参与到讨论中来。   

你可能感兴趣的:([Project Euler] 来做欧拉项目练习题吧: 题目006)