Project Euler——Problem 2 - Daybreakcx's Blog - Keep Programming! With Algorithm! With Fun!
Project Euler——Problem 2
daybreakcx
posted @ 2009年7月14日 00:33
in Prject Euler
, 842 阅读
原题与答案:
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的偶数斐波那契数列项的和,笔算我没想到好方法,直接给出程序的运算方法吧:
-
#include<stdio.h>
-
int sum=2,a=1,b=2,i;
-
int main()
-
{
-
for (i=3;;i++)
-
if (i&1)
-
{
-
a+=b;
-
if (a>4000000) break;
-
if (!(a&1)) sum+=a;
-
}
-
else
-
{
-
b+=a;
-
if (b>4000000) break;
-
if (!(b&1)) sum+=b;
-
}
-
return 0;
-
}