###ProjectEuler 的一道簡單題目
[ProjectEuler](http://projecteuler.net) 上的第六題是比較簡單的一道習(xí)題炸裆,復(fù)述題目如下:
> 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.
#### ?重述題目
所述的意思是計算平方和與和的平方的差異粤剧,題目中舉出了一個例子.就是分別計算自然數(shù)1到10的平方和與和的平方浮禾,然后做減法瑞你,所得的結(jié)果 2640 就是所求的結(jié)果. 題目要求計算自然數(shù) 1 到 100 的計算結(jié)果.
####分析題目
如果直接進行計算招狸,可以利用計算機直接循環(huán)贤惯,分別直接計算出平方的和與和的平方,然后做差纸巷,就得到題目要求的結(jié)果. 顯而易見的是,這樣的方法比較簡單粗魯眶痰,但是計算過程中做了許多不需要的工作.<br/>
?簡化計算的方法是提前化簡出通項公式瘤旨,然后帶入項數(shù)獲得答案.問題的關(guān)鍵就是如何化簡公式
####平方和的計算
大家都知道 $1+2+\cdots +n = \frac{n(n+1)}{2}$ ,但是如何計算 $1^2 + 2^2 + 3^2 + \cdots + n^2$ 根據(jù)數(shù)學(xué)定理可知 計算的結(jié)果是一個關(guān)于 $n$ 的三次表達式,一次我們只需求出這個多項式的四個參數(shù)竖伯,我們就獲得了平方和計算的表達式存哲;$$\begin{bmatrix}1&1&1&1\\2^3&2^2&2&1\\3^3&3^2&3&1\\4^3&4^2&4&1\end{bmatrix} \times \begin{bmatrix}a\\b\\c\\d\end{bmatrix}=\begin{bmatrix}1\\5\\14\\30\end{bmatrix}$$獲得矩陣的解即為平方和多項式的系數(shù),所以平方和通項表達式為$$1^2+2^2+3^2+\cdots +n^2=\frac{n^3}{3}+\frac{n^2}{2}+\frac{n}{6}$$
####和的平方
因為$$1+2+3+\cdots+n=\frac{n(n+1)}{2}$$七婴,所以$$(1+2+3+\cdots+n)^2=\frac{n^2(n+1)^2}{4}$$.
####求差
將兩個多項式做差宏胯,結(jié)果為$$\frac{n^3}{3}+\frac{n^2}{2}+\frac{n}{6}-\frac{n^2(n+1)^2}{4}=-\frac{n^4}{4}-\frac{n^3}{6}+\frac{n^2}{4}+\frac{n}{6}$$
####求解
直接將 $n=100$ 帶入,獲得解為 25164150. 這樣問題就解決了.(偷個懶本姥,不想寫長的代碼,直接在 chrome ?瀏覽器下運行js算出結(jié)果.)
```javascript
var n =100;
Math.pow(n,4)/4 +Math.pow(n,3)/6-n*n/4-n/6;
```