Problem 2 from Project Euler
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.
————————————————
Round 2 and seemed to be a little easier this time. I’m not really happy with having to prime the array as I did, I think there is probably a more elegant solution than what I came up with.
using System;
using System.Collections;
using System.Text;
namespace EulerProblem2
{
class Program
{
static void Main(string[] args)
{
getList();
}
public static int getList()
{
// array list and array to store even numbers of the Fibonacci sequence. Will use array to add arraylist up.
ArrayList listEven = new ArrayList();
int i = 0, sum = 0;
int[] numArray = new int[11];
// ***** priming the array with first even int, need to find a better way to prime the array. *********
numArray[0] = 2;
++i;
// declaring variables used in the while loop.
int firstNum = 1, secondNum = 2, numHolder = 0;
bool isEven = false;
//while loop checks to see if the addition of 2 numbers under 4 mill are even, and if they are stores them in the array.
while (firstNum < 4000000)
{
numHolder = firstNum + secondNum;
if (numHolder % 2 == 0)
{
isEven = true;
numArray[i] = numHolder;
++i;
}
else
isEven = false;
Console.WriteLine("The first value of " + firstNum + " plus the second value " + secondNum + " equals: " + numHolder + " Number is even: " + isEven);
firstNum = secondNum;
secondNum = numHolder;
}
// adds array to arraylist
listEven.AddRange(numArray);
Console.ReadLine();
Console.WriteLine("Show list of even numbers and add them together");
//loop show's the list of even numbers and adds them together to get total sum of Fibonacci sequence.
foreach (int item in numArray)
{
Console.Write(item + "\n");
sum = item + sum;
}
Console.ReadLine();
Console.WriteLine("The sum off all even numbers is: {0}", sum);
Console.ReadLine();
return 0;
}
}
}