Here is the first tentative using brute force.
public long sum() {
long sum = 0;
for (int i = 1; i < 1000000; i++) {
long fibNum = fib(i);
if (fibNum > 4000000) {
break;
}
if (isEven(fibNum)) {
sum += fibNum;
}
}
return sum;
}
private boolean isEven(long n) {
return (n % 2) == 0;
}
private long fib(long n) {
return (n < 2) ? n : fib(n - 1) + fib(n - 2);
}
And here is the second tentative using a little big of math magic.
public long sum(double limit) {
long n = Math.round(((Math.log(limit * Math.sqrt(5))) * 2) + 1.618);
long sum = 0;
for (long i = 6; i < n; i++) {
long fib = (4 * fib(i - 3)) + fib(i - 6);
if (fib % 2 == 0)
sum += fib;
}
return sum + 2;
}
private long fib(long n) {
return (n < 2) ? n : fib(n - 1) + fib(n - 2);
}
No comments:
Post a Comment