This is from project Euler, problem 2. I wrote the following seemingly innocent code:
public class FibonacciEven {
public static void main(String[] stuff) {
long sum = 0;
int i = 0;
while(fib(i) <= 40) {
boolean even = fib(i) % 2 == 0;
if(even) {
sum += fib(i);
}
else {
continue;
}
i++;
}
System.out.println(sum);
}
public static long fib(int n) {
long prev1 = 0;
long prev2 = 1;
for(int i = 0; i < n; i++) {
long savePrev1 = prev1;
prev1 = prev2;
prev2 = savePrev1 + prev2;
}
return prev1;
}
}
I did read about how the Java method for working out Fibonacci numbers is quite memory hungry, but, as you can see, I scaled my limit down to 40, and it still doesn’t get to the end, so I assume that I have gotten some syntax horribly wrong. What bit of the code is making it run forever? And if all of this really is due to the fact that the method takes so much time to run, can anyone suggest a better way?
EDIT: ok, now my code looks like this:
public class FibonacciEven {
public static void main(String[] stuff) {
long sum = 0;
int i = 0;
while(fib(i) <= 40) {
boolean even = fib(i) % 2 == 0;
if(even) {
sum += fib(i);
}
i++;
}
System.out.println(sum);
}
public static long fib(int n) {
long prev1 = 0;
long prev2 = 1;
for(int i = 0; i < n; i++) {
long savePrev1 = prev1;
prev1 = prev2;
prev2 = savePrev1 + prev2;
}
return prev1;
}
}
This time it ignores the 2 (index 3) in the Fibonacci sequence.
If
evenis false, you end up continuin without updatingi– so it’ll loop round again and do exactly the same work again, soevenwill be false again, etc…I suspect you just want to take out the
elseblock.