斐波那契数列中不超过400万的偶数之和

/**
* 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.
*/

代码:

private static int sumEvenFib(int N) {
if (N < 2)
return 0;
if (N < 8)
return 8;
int sum = 10, ppre = 2, pre = 8;
int tmp = ppre + 4 * pre;
while (tmp < N) {
sum += tmp;
ppre = pre;
pre = tmp;
tmp = ppre + 4 * pre;
}
return sum;
}

public static void main(String[] args) {
print(sumEvenFib(4000000));
}

思想:

最基本的做法就是一项项迭代,然后判断该项是否偶数然后相加,这样需做n次计算

斐波那契数列中的偶数只可能是A3n+2 项,我们只要找数列中的偶数和,那么找到数列中偶数之间的关系,则只需计算n/3,可以减少2倍的时间

经求有A3n+2=4*A3n-1+A3n-4