Project Euler——Problem 2 - Daybreakcx's Blog - Keep Programming! With Algorithm! With Fun!
Project Euler——Problem 1
Project Euler——Problem 3

Project Euler——Problem 2

daybreakcx posted @ 2009年7月14日 00:33 in Prject Euler , 573 阅读

原题与答案:

Problem 2

19 October 2001

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

Find the sum of all the even-valued terms in the sequence which do not exceed four million.

Answer:4613732

 

分析与解答:

这个题目也是简单的模拟,即求不超过4000000的偶数斐波那契数列项的和,笔算我没想到好方法,直接给出程序的运算方法吧:

 

  1. #include<stdio.h>
  2. int sum=2,a=1,b=2,i;
  3. int main()
  4. {
  5.         for (i=3;;i++)
  6.                 if (i&1)
  7.                 {
  8.                         a+=b;
  9.                         if (a>4000000) break;
  10.                         if (!(a&1)) sum+=a;
  11.                 }
  12.                 else
  13.                 {
  14.                         b+=a;
  15.                         if (b>4000000) break;
  16.                         if (!(b&1)) sum+=b;
  17.                 }
  18.         printf("%d\n",sum);
  19.         return 0;
  20. }

 

 


登录 *


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