题目
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.
在斐波那契数列中,找出4百万以下的项中值为偶数的项之和。
斐波那契数列中的每一项被定义为前两项之和。从1和2开始,斐波那契数列的前十项为:1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
考虑斐波那契数列中数值不超过4百万的项,找出这些项中值为偶数的项之和。
解答:这题也比较简单,该题数据比较小,如果数据比较大时就要注意数据类型的长度和大小范围,如果想了解可以参考http://blog.csdn.net/tabyou/article/details/20214819
Java程序代码如下
public class N_2 {
public static void main(String []args)
{
int a = 1,b=2;
int sum = 0;
while(b<4000000)
{
if(b%2==0)
{
sum += b;
}
b = a+b;
a = b-a;
}
System.out.println(sum);
}
}
运行结果:4613732