Problem 2 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, …
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
問題 2 偶數斐波那契數
斐波那契數列中的每個新項都是通過添加前兩項來生成的。從 1 和 2 開始,前 10 個術語将是:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …
通過考慮斐波那契數列中值不超過四百萬的項,求偶數項之和。
思路分析
斐波那契數列
首先清楚什麼是斐波那契數列
斐波那契數(Successione di Fibonacci),又譯為菲波拿契數、菲波那西數、斐氏數、黃金分割數。所形成的數列稱為斐波那契數列
數學定義
數學上,使用遞歸的方法定義
通俗來講,斐波那契數列由 0(第零項) 和 1 開始,之後的斐波那契數由之前的兩數相加得出,舉例
1、 1、 2、 3、 5、 8、 13、 21、 34、 55、 89、 144、 233、 377……
解題報告
正常
看到這麼多數字,并且有一定規律,我們自然而然會聯想到數組。利用其數學定義解決,關鍵在于第三個斐波那契數值等于前兩個數值相加,而後一直如此,實作如下
/*
* @Author: coder-jason
* @Date: 2022-04-05 12:26:31
* @LastEditTime: 2022-04-05 14:05:48
*/
#include <iostream>
using namespace std;
int main()
{
int f[1000], sum = 0;
f[0] = 2; // 由循環中等式導出的結果
f[1] = 1;
f[2] = 2; //初始化數組前三個元素,其他預設為 0
while (f[f[0]] < 4000000)
{ //數組第一個元素的值小于 4000000
f[f[0] + 1] = f[f[0]] + f[f[0] - 1]; // 首先了解 F[3]=F[2]+F[1] 然後類比到數組,用元素 f[0] 代換即可
f[0]++; //每計算得出一個斐波那契數,數組第一個元素加 1(記錄共有多少個斐波那契數)
}
for (int i = 0; i < f[0]; i++)
{
if (f[i] % 2 == 0)
{
sum += f[i];
}
}
cout << sum << endl;
return 0;
}
優化
/*
* @Author: coder-jason
* @Date: 2022-04-05 12:26:31
* @LastEditTime: 2022-04-05 14:20:43
*/
#include <iostream>
using namespace std;
int main()
{
int f[3], sum = 0;
f[0] = 1;
f[1] = 2;
for (int i = 2; f[2] < 4000000; i++)
{
f[2] = f[1] + f[0];
f[0] = f[1];
f[1] = f[2]; // 後續數字依次向前推進,在前三個元素中進行計算
if (f[2] % 2 == 0)
{
sum += f[2];
}
}
//由于 sum 計算的是偶數項的和,但是前三個數字 1 ,2 ,3 中
// 2 是斐波那契數,但是 3%2 不為 0 ,sum 此時并未計算斐波那契數 2,結果需要加上
cout << sum + 2 << endl;
return 0;
}