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, …
Find the sum of all the even-valued terms in the sequence which do not exceed four million.
By definition, aren’t the first two Fibonacci numbers 0 and 1? Each next number is the sum of the previous two, blah blah blah. Guess we’ll have to provide code to trim the leading 0 and 1.
public class Euler2
{
public static void main(String[] args)
{
Euler2 e = new Euler2();
System.out.print(“Problem 2:\nSum of Even = ” + e.Problem2()+ “\n”);
}public String Problem2 ()
{
int a=0;
int b=1;
int step = 1;
int sum = 0;
while (a < 4000000)
{
if (step > 2)
{
if (a % 2 == 0)
{
sum += a;
}
}
a=a+b;
b=a-b;
step++;
}
return String.valueOf(sum);
}
}