Even Fibonacci numbers
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.
1.利用数组求fib数列
- 开一个足够大的数组,并初始化前两项1,2
- 通过递推法逐个将斐波那契数列的每一项存入数组
- 将所有为偶数的项的数字相加
1 |
|
2.两个变量求fib数列
- 不需要定义数组,在运算的过程中就可以知道哪些项是偶数
- 计算过程中只保留两个数字:前一个数 和 后一个数,两个数循环相加即可
1 |
|
3.总结:
相对于方法1,方法2同时正向、反向利用了斐波那契数列项之间的关系,
从而避免了开辟数组空间,减小了算法的空间复杂度。在关于斐波那契数列的问题时要灵活运用项之间的关系
1 | while(b < 4000000){ |
1 | while(b < 4000000){ |
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.