だから私はC++を学んでいます。「C++プログラミング言語」と「EffectiveC++」を入手し、ProjectEulerを実行しています。問題1...ダンゾ。問題2...それほど多くはありません。Win32コンソールアプリでVS2008を使用しています。
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:
フィボナッチ数列の新しい各項は、前の2つの項を追加することによって生成されます。1と2から始めると、最初の10項は次のようになります。
1、2、3、5、8、13、21、34、55、89、..。
400万を超えないシーケンス内のすべての偶数値の項の合計を見つけます。
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
したがって、デバッグコードの3つの列があります...生成関数から返される数値、(int)generatedNumber、および(int)generatedNumber%2
つまり、第11学期には、
55,54,0
(int)55 = 54なのはなぜですか?