欧拉计划002--偶斐波那契数
首先看一下题目
Even Fibonacci numbers
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,\cdots \]By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
偶斐波那契数
斐波那契数列中的每一项都是前两项的和。由1和2开始生成的斐波那契数列的前\(10\)项为:
\[1,2,3,5,8,13,21,34,55,89,\cdots \]考虑该斐波那契数列中不超过四百万的项,求其中为偶数的项之和。
解题思路:
其实这一道题,就是单纯的遍历一次,并没有取巧的方法。退出循环的条件条件就是Fibonacci[i] > 4000000
。判断是否为偶数的方法就是如果i%2==0
成立,那么i
就为偶数。
#include <iostream>
using namespace std;
long long Fibonacci[1000] = {1, 2};
long long sum = 2;
int main() {
for (int i = 3; ; i ++) {
Fibonacci[i] = Fibonacci[i-2] + Fibonacci[i-1];
if (Fibonacci[i] > 4000000)
break;
if (Fibonacci[i] % 2 == 0)
sum += Fibonacci[i];
}
cout << sum << endl;
return 0;
}
最后算出来的结果为7049156。