Reputation: 23
Some of you may be familiar with ProjectEuler; a website/community containing a series of logistic number based puzzles which one can solve through use of code. They have a question reading "By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms" I produced the following code as a solution
int firstNumber = 0;
int Total = 0;
for (int fib = 0; fib < 4000000; fib+=firstNumber)
{
firstNumber += fib;
if (fib % 2 == 0)
{
total += fib
}
}
The IDE's i tried were unable to execute this however. I'm almost completely new to programming and the course I'm doing in school begins directly with object oriented programming so I don't have much of a computer science background to go on. As you can see, theoretically the code I have provided should change the increment to the previous value, hence creating the fibonacci sequence, and adding each even number to the total should provide me with the answer, right? Logistically it seems appropriate but I i'm far from a software engineer, i really have no idea what I'm doing. So, I suppose my question is, what exactly is wrong with my code and how might you approach the solution of the problem? Thanks, Adam.
Upvotes: 2
Views: 138
Reputation: 32296
There are two problems with your solution. First you're starting both terms at 0 and adding 0 to 0 just results in 0. You should start both at 1 instead. Second is the fact that your current term is alternating between fib
and firstNumber
. You need a temporary value to put the sum of both into then set firstNubmer
to fib
and then fib
to the temporary value. So, you really can just use a while
loop instead.
int firstNumber = 1;
int fib = 1;
int Total = 0;
while(fib < 4000000)
{
if (fib % 2 == 0)
{
total += fib;
}
int temp = firstNumber + fib;
firstNumber = fib;
fib = temp;
}
But here's how I solved the same issue. Note this gives you a method that can be reused for other Euler problems. Also note that instead of using a temporary variable I add the previous term to the current to get the next then subtracting the previous from the current will result in the the value of current before adding previous to it.
public static IEnumerable<long> FibSeries()
{
yield return 1;
long previous = 1;
long current = 1;
while (true)
{
yield return current;
current += previous;
previous = current - previous;
}
}
And then you can solve it with Linq
long sum = FibSeries().TakeWhile(f => f < 4000000).Where(f => f % 2 == 0).Sum();
Upvotes: 2