Project Euler——Problem 6 - Daybreakcx's Blog - Keep Programming! With Algorithm! With Fun!
Project Euler——Problem 5
Project Euler——Problem 7

Project Euler——Problem 6

daybreakcx posted @ 2009年7月17日 20:57 in Prject Euler , 1200 阅读

原题与答案:

Problem 6

14 December 2001

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.

Answer:25164150

 

分析与解答:

这个题目是求1到100的和平方与平方和的差,我们可以很容易地利用求出通项公式。首先是和平方:(1+2+...+n)^2=[\dfrac{n*(n+1)}{2}]^2=\dfrac{n^2*(n+1)^2}{4},然后是平方和:1^2+2^2+...+n^2=\dfrac{n*(n+1)*(2*n+1)}{6},最后是他们的差:(1+2+...+n)^2-(1^2+2^2+...+n^2)=\dfrac{n^2*(n+1)^2}{4}-\dfrac{n*(n+1)*(2*n+1)}{6}=\dfrac{n*(n+1)*(n-1)*(3*n+2)}{12}。于是带入公式就可以得到结果,当然用程序这个题目也是很容易实现的,源代码如下所示:

 

  1. #include<stdio.h>
  2. int res=0,i;
  3. int main()
  4. {
  5.         for (i=1;i<=100;i++)
  6.                 res+=i;
  7.         res*=res;
  8.         for (i=1;i<=100;i++)
  9.                 res-=i*i;
  10.         printf("%d\n",res);
  11.         return 0;
  12. }

 

 

.. 说:
2010年7月20日 03:41

菜鸟问一句:第二个平方和的公式是怎么推导出来的?请问是哪方面的数学知识……

Avatar_small
daybreakcx 说:
2010年7月24日 03:43

实际上n次的连续自然数平方和是一个n+1次的多项式,这是我在初中时不知道听谁说的,后来也老这么用了,至于推导,网络上有很多,可以搜索一下

.. 说:
2010年7月24日 17:55

第二个分式的分母应该是6,你好像写错了。

Avatar_small
daybreakcx 说:
2011年1月27日 03:31

多谢指正,已改过^_^


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter