Reputation: 7
public class Fibonaccisequence {
public static void main(String args[]){
int term[] = new int[]{1,2};
int termValue = term[0]+term[1];
int sum = 0;
while(termValue <= 4000000)
{
termValue = term[0]+term[1];
if (term[1]%2==0)
{sum=sum+term[0];}
int a= term[1];
term[1]=termValue;
term[0]=a;
}
System.out.println(sum);
}
}
Problem detail: 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
I got 2851443 as answer, and I checked my code many times.
Upvotes: 0
Views: 46
Reputation: 11832
A problem exists in this code:
if (term[1]%2==0)
{sum=sum+term[0];}
If you detect that term[1] is even, you should be adding it to the sum, not the previous value:
if (term[1] % 2 == 0) {
sum = sum + term[1]; // add term[1], not term[0]
}
Upvotes: 1