Sunday, August 23, 2009

Project Euler Problem 2

Woohoo! I was able to get the second problem right on the first try as well.


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

public class PE0002
{
public static void main(String[] args)
{
long[] fibonacciSequence = createFibonacciSequence();
long sum = 0;

for (Long currentNumberInSequence : fibonacciSequence)
if (isEven(currentNumberInSequence))
sum += currentNumberInSequence;

System.out.println(sum);
}

private static long[] createFibonacciSequence()
{
long[] fibonacciSequence = new long[33]; // originally set to 100000

fibonacciSequence[0] = 1l;
fibonacciSequence[1] = 2l;

int index = 2;
long currentNumberInSequence = 2l;

while (currentNumberInSequence <= 4000000)
{
fibonacciSequence[index] = fibonacciSequence[index - 1] + fibonacciSequence[index - 2];
currentNumberInSequence = fibonacciSequence[index];
index++;
}

return fibonacciSequence;
}

private static boolean isEven(long number)
{
return number % 2 == 0;
}
}

No comments:

Post a Comment