Files
ProjectEulerCS/ProjectEulerCS/Problems/Problem2.cs

92 lines
2.6 KiB
C#

//ProjectEuler/ProjectEulerCS/src/Problems/Problem2.cs
//Matthew Ellison
// Created: 08-23-20
//Modified: 08-23-20
//The sum of the even Fibonacci numbers less than 4,000,000
//Unless otherwise listed all non-standard includes are my own creation and available from https://bibucket.org/Mattrixwv/CSClasses
/*
Copyright (C) 2020 Matthew Ellison
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System.Collections.Generic;
namespace ProjectEulerCS.Problems{
public class Problem2 : Problem{
//Variables
//Static variables
private const int TOP_NUM = 4000000 - 1; //The largest number that will be checked as a fibonacci number
//Instance variables
private int fullSum; //Holds the sum of all the numbers
public int Sum{
get{
if(!solved){
throw new Unsolved();
}
return fullSum;
}
}
//Functions
//Constructor
public Problem2() : base("What is the sum of the even Fibonacci numbers less than 4,000,000?"){
fullSum = 0;
}
//Operational functions
//Solve the problem
public override void Solve(){
//If the problem has already been solved do nothing and end the function
if(solved){
return;
}
//Start the timer
_timer.Start();
//Get a list of all fibonacci numbers < 4,000,000
List<int> fibNums = mee.Algorithms.GetAllFib(TOP_NUM);
//Step through every element in the list checkint if it is even
foreach(int num in fibNums){
//If the number is even add it to the running tally
if((num % 2) == 0){
fullSum += num;
}
}
//Stop the timer
_timer.Stop();
//Throw a flag to show the problem is solved
solved = true;
//Save the results
_result = "The sum of all even fibonacci numbers <= " + TOP_NUM + " is " + fullSum;
}
//Reset the problem so it can be run again
public override void Reset(){
base.Reset();
fullSum = 0;
}
}
}
/* Results:
The sum of all even fibonacci numbers <= 3999999 is 4613732
It took an average of 5.810 microseconds to run this problem through 100 iterations
*/