我尝试了很多次,但我似乎无法弄清楚我做错了什么。这是我最近尝试解决的问题之一。
我知道其他来源的正确答案是4613732
。
/*
* 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.
*/
public class problem2
{
public static void main(String args[])
{
int sum = 0;
int[] anArray = new int[4000000];
anArray[0] = 1;
anArray[1] = 2;
for (int i = 2; i <= anArray.length - 1; i++) {
anArray[i] = anArray[i - 1] + anArray[i - 2];
if (anArray[i] % 2 == 0 && anArray[i] <= 4000000) {
sum += anArray[i];
}
}
System.out.println(sum);
}
}