美文网首页
ProjectEuler 的一道简单题目.md

ProjectEuler 的一道简单题目.md

作者: hahah | 来源:发表于2014-07-12 20:10 被阅读0次

###ProjectEuler 的一道简单题目

[ProjectEuler](http://projecteuler.net) 上的第六题是比较简单的一道习题,复述题目如下:

> 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到10的平方和与和的平方,然后做减法,所得的结果 2640 就是所求的结果. 题目要求计算自然数 1 到 100  的计算结果.

####分析题目

如果直接进行计算,可以利用计算机直接循环,分别直接计算出平方的和与和的平方,然后做差,就得到题目要求的结果. 显而易见的是,这样的方法比较简单粗鲁,但是计算过程中做了许多不需要的工作.<br/>

 简化计算的方法是提前化简出通项公式,然后带入项数获得答案.问题的关键就是如何化简公式

####平方和的计算

大家都知道 $1+2+\cdots +n = \frac{n(n+1)}{2}$ ,但是如何计算 $1^2 + 2^2 + 3^2 + \cdots + n^2$ 根据数学定理可知 计算的结果是一个关于 $n$ 的三次表达式,一次我们只需求出这个多项式的四个参数,我们就获得了平方和计算的表达式;$$\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}$$获得矩阵的解即为平方和多项式的系数,所以平方和通项表达式为$$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}$$.

####求差

将两个多项式做差,结果为$$\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算出结果.)

```javascript

var n =100;

Math.pow(n,4)/4 +Math.pow(n,3)/6-n*n/4-n/6;

```

相关文章

网友评论

      本文标题:ProjectEuler 的一道简单题目.md

      本文链接:https://www.haomeiwen.com/subject/sxfstttx.html