mirror of
https://bitbucket.org/Mattrixwv/octavefunctions.git
synced 2026-02-04 04:02:32 -05:00
Added cpp for Problem 2
This commit is contained in:
43
ProjectEuler/C++/Problem2.cpp
Normal file
43
ProjectEuler/C++/Problem2.cpp
Normal file
@@ -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 <iostream>
|
||||||
|
#include <vector>
|
||||||
|
#include <chrono>
|
||||||
|
|
||||||
|
|
||||||
|
int main(){
|
||||||
|
unsigned long fullSum = 2; //Holds the sum of all the numbers
|
||||||
|
std::vector<unsigned long> 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<std::chrono::nanoseconds>(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;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user