【发布时间】:2010-10-07 22:14:35
【问题描述】:
所以我正在学习 C++。我已经完成了“C++ 编程语言”和“Effective C++”,并且正在运行 Project Euler。问题 1...邓佐。问题2...不是那么多。我正在使用 VS2008 的 Win32 控制台应用程序。
低于 400 万的斐波那契数列的所有偶数项的总和是多少?
它不起作用,所以我减少到 100 个测试用例...
这是我写的……
// Problem2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
cout << "Project Euler Problem 2:\n\n";
cout << "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:\n\n";
cout << "1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...\n\n";
cout << "Find the sum of all the even-valued terms in the sequence which do not exceed four million.\n\n";
cout << "Answer: " << Solve();
}
double Solve() {
int FibIndex = 0;
double result = 0.0;
double currentFib = GenerateNthFibonacciNumber(FibIndex);
while (currentFib < 100.0){
cout << currentFib << " " << (int)currentFib << " " << (int)currentFib % 2 << "\n";
if ((int)currentFib % 2 == 0){
result += currentFib;
cout<<(int)currentFib;
}
currentFib = GenerateNthFibonacciNumber(++FibIndex);
}
return result;
}
double GenerateNthFibonacciNumber(const int n){
//This generates the nth Fibonacci Number using Binet's Formula
const double PHI = (1.0 + sqrt(5.0)) / 2.0;
return ((pow(PHI,n)-pow(-1.0/PHI,n)) / sqrt(5.0));
}
这是输出...
欧拉计划问题2:
斐波那契的每个新术语 序列是通过添加 前两期。从 1 开始 和 2,前 10 个术语将是:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
求所有偶值的总和 序列中的项不 超过四百万。
0 0 0
1 1 1
1 1 1
2 2 0
3 3 1
5 5 1
8 8 0
13 13 1
21 21 1
34 34 0
55 54 0
89 89 1
答案:99
所以我有三列调试代码...从生成函数返回的数字,(int)generatedNumber 和 (int)generatedNumber % 2
所以在第 11 个学期我们有
55,54,0
为什么 (int)55 = 54?
【问题讨论】:
-
FWIW,斐波那契数列通常以 0. 0,1,1,2,3,5,...
-
这是欧拉计划的错,我同意你的看法。我写的算法确实生成了前导 0,1。但这不会对答案造成任何问题(因为它正在寻找偶数项的总和)
-
由于 double 类型本身具有有限的精度,因此您应该小心将其用于此类事情,因为 Binet 公式使用无限精度来获得结果。