尤拉計劃002--偶斐波那契數
阿新 • • 發佈:2021-09-19
尤拉計劃002--偶斐波那契數
首先看一下題目
Even Fibonacci numbers
\[1,2,3,5,8,13,21,34,55,89,\cdots \]
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: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。