- #1
newfeeling
- 2
- 0
Homework Statement
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.
Homework Equations
n/a
The Attempt at a Solution
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
int n;
int fibnum;
int sum;
int num2;
int num1;
int limit;
num2 = 1;
num1 = 0;
fibnum = 0;
sum = 0;
cout << "n?" << endl;
cin >> limit;
for(n = 0; n < limit; n += 1)
{
fibnum = num2 + num1;
if(fibnum % 2 == 0)
{
sum += fibnum;
}
num1 = num2;
num2 = fibnum;
}
cout << sum << endl;
return EXIT_SUCCESS;
}This chunk of code allows me to get the correct sum when "limit" is a relatively small number (e.g. 10 will return 44 and 5 will return 10), but doesn't work for really big numbers...like 4,000,000. I'm not looking for a solution; I know that if my algorithm were designed correctly I would have already gotten the correct answer, but clearly there is some glaring flaw that I'm not noticing. Am I on the right track with this method at least, or am I wasting my time beating my head over my desk with this approach?