Problem 2
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.
Mmmm Fibonacci. I've liked the Fibonacci sequence since grade eight or so. No idea why.
The way I see it, this problem can be solved in a similar way to the last. Generate each new number, check its compatibility with the rules and add it to a running total if it fits.
Pseudo-code
while thisNumber < maximum if thisNumber is divisible by 2 total += thisNumber thisNumber = previousNumber + previousPreviousNumber previousPreviousNumber = previousNumber previousNumber = thisNumber print total
Looks fairly simple! Let's give it a go in Java. Here's my implementation:
public class Problem2 {
public static void main(String[] args) {
long runningTotal = 0;
long previousNumber = 1;
long previousPreviousNumber = 1;
long currentNumber = 1;
while (currentNumber < 4000000) {
if (currentNumber % 2 == 0) {
runningTotal += currentNumber;
}
currentNumber = previousNumber + previousPreviousNumber;
previousPreviousNumber = previousNumber;
previousNumber = currentNumber;
}
System.out.println(runningTotal);
}
}
This gives the result "4613732" which turns out to be correct.
In review, this approach was a bit clumsy. Using recursion would have been more appropriate in this case because every iteration of the loop uses data from the previous iteration and there is an easy point of termination.
Here is my implementation of a recursive method of finding the solution. I have no idea which is more efficient but I'd like to know.
public class Problem2 {
public static void main(String[] args) {
System.out.println(recursionTest(1, 1));
}
public static long recursionTest(long previous, long pprevious) {
long currentNumber = previous + pprevious;
if (currentNumber < 4000000) {
if (previous % 2 == 0) {
return previous + recursionTest(currentNumber, previous);
} else {
return recursionTest(currentNumber, previous);
}
} else {
return previous;
}
}
}
In the end I don't really mind if this is less efficient. It looks nicer, is more interesting to write, and I think it's more elegant. If I was doing this as a part of something bigger I might spend time optimising it but as this is stand-alone code and it compiles and runs in less than a second I'm happy. When things start taking more than a minute to run I might start to look at optimisation but until then I'm not going to bother.
No comments:
Post a Comment