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.
1. 第2个问题 : 偶数的斐波那契数
斐波那契序列的每一项都是它前两个项相加之和。从前两项1和2开始,前10个项是:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …
通过考虑斐波那契序列中值不超过400万的项,找出值为偶数的项的和。
2. 求解分析
从题目中,我们知道:斐波那契序列的计算公式是: Fn = Fn-1 + Fn-2 (n>=3),其中F1 =1, F2 = 2
知道了Fn的计算公式,我们判断每一个值是偶数的Fn项,并求和。
3. C++ 代码实现
我们定义了一个类PE0002,包含一个成员函数getSumOfEvenValuedTerms(),这个函数有一个输入参数max,返回值小于max的项的和。
C++ 代码
#include <iostream>
#include <cassert>
using namespace std;
class PE0002
{
public:
int getSumOfEvenValuedTerms(int max);
};
int PE0002::getSumOfEvenValuedTerms(int max)
{
int Fn_2 = 1; // first term
int Fn_1 = 2; // second term
int Fn; // next term
int sum = Fn_1; // 2 is the first even-valued term
while (Fn_2 + Fn_1 <= max)
{
Fn = Fn_2 + Fn_1;
if (0 == Fn % 2) // Fn is an even-valued term
{
sum += Fn;
}
Fn_2 = Fn_1;
Fn_1 = Fn;
}
return sum;
}
int main()
{
PE0002 pe0002;
assert(44 == pe0002.getSumOfEvenValuedTerms(89));
cout << "The sum of the even-valued terms in Fibonacci sequence " << endl;
cout << "whose values do not exceed four million is " ;
cout << pe0002.getSumOfEvenValuedTerms(4000000) << "." << endl;
return 0;
}
4. Python 代码实现
Python采用了和C++类似的方法,我们也定义了一个函数FibonacciEvenValuedTermsSum()。
Python 代码
def FibonacciEvenValuedTermsSum(max):
Fn_2, Fn_1 = 1, 2
sumOfTerms = 2
while Fn_1 + Fn_2 <= max:
Fn = Fn_1 + Fn_2
if Fn % 2 == 0:
sumOfTerms += Fn
Fn_2, Fn_1 = Fn_1, Fn
return sumOfTerms
def main():
assert 44 == FibonacciEvenValuedTermsSum(89)
print("The sum of the even-valued terms is",
FibonacciEvenValuedTermsSum(4000000))
if __name__ == '__main__':
main()