From d44eb0b886f83fa75a5aad454b4c6ec090dd5633 Mon Sep 17 00:00:00 2001 From: Matthew Ellison Date: Thu, 27 Sep 2018 01:36:48 -0400 Subject: [PATCH] Added cpp for Problem 2 --- ProjectEuler/C++/Problem2.cpp | 43 +++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 ProjectEuler/C++/Problem2.cpp diff --git a/ProjectEuler/C++/Problem2.cpp b/ProjectEuler/C++/Problem2.cpp new file mode 100644 index 0000000..e013484 --- /dev/null +++ b/ProjectEuler/C++/Problem2.cpp @@ -0,0 +1,43 @@ +//ProjectEuler/C++/Problem2.cpp +//Matthew Ellison +// Created: 9-28-18 +//Modified: 9-28-18 +//The sum of the even Fibonacci numbers less than 4,000,000 + + +#include +#include +#include + + +int main(){ + unsigned long fullSum = 2; //Holds the sum of all the numbers + std::vector fib = {1, 1}; //Holds the Fibonacci numbers + unsigned long nextFib = 2; //Holds the next Fibonacci number + + std::chrono::high_resolution_clock::time_point startTime = std::chrono::high_resolution_clock::now(); //Start the timer + while(nextFib < 4000000){ + //If it is an even number add it to the sum + if(nextFib % 2){ + fullSum += nextFib; + } + //Move all the fib numbers down and calculate the next one + fib.at(0) = fib.at(1); + fib.at(1) = nextFib; + nextFib = fib.at(1) + fib.at(0); + //You could do this keeping all the fib numbers and sum at the end, + //but this way will be faster because you are only handling every number twice + //and you don't have to expand the vector + } + //Calculate the time needed for the algorithm + std::chrono::high_resolution_clock::time_point endTime = std::chrono::high_resolution_clock::now(); //End the timer + std::chrono::high_resolution_clock::duration dur = std::chrono::duration_cast(endTime - startTime); + + //Print the resultss + std::cout << "The sum of the even Fibonacci numbers less than 4,000,000 is " << fullSum + << "\nIt took " << dur.count() << " nanoseconds to run this algorithm" << std::endl; + + //Pause before ending + std::cin.get(); + return 0; +} \ No newline at end of file