From 0bec0ff5ab8223a9231694424ae0dc6fae5149af Mon Sep 17 00:00:00 2001 From: Matthew Ellison Date: Fri, 8 Feb 2019 15:34:20 -0500 Subject: [PATCH] Added getAllFib function to return a vector of Fibonacci numbers --- Algorithms.hpp | 45 ++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 40 insertions(+), 5 deletions(-) diff --git a/Algorithms.hpp b/Algorithms.hpp index 909bb40..1d4a22d 100644 --- a/Algorithms.hpp +++ b/Algorithms.hpp @@ -64,12 +64,16 @@ bool isFound(T num, std::vector list); //It can however be used with num if you want the first num characters to be stationary std::vector getPermutations(std::string master, int num = 0); //These functions return the numth Fibonacci number -uint64_t getFib(uint64_t num); +template +T getFib(T num); //In order to use this functionality you must use the -DNEEDGMP flag in your compiler //You must also link both libgmpxx and libgmp #ifdef NEEDGMP mpz_class getMpzFib(uint64_t num); #endif //NEEDGMP +//This function returns a vector that includes all Fibonacci numbers <= num +template +std::vector getAllFib(const T num); //This is a function that performs a bubble sort on a vector template bool bubbleSort(std::vector nums); @@ -277,21 +281,23 @@ std::vector getPermutations(std::string master, int num){ return perms; } -uint64_t getFib(uint64_t num){ +template +T getFib(T num){ //Make sure the number is within bounds if(num <= 2){ return 1; } //Setup the variables - uint64_t fib = 0; - uint64_t tempNums[3]; + T fib = 0; + T tempNums[3]; tempNums[0] = tempNums[1] = 1; //Do the calculation - for(uint64_t cnt = 2;cnt < num;++cnt){ + for(T cnt = 2;(cnt < num) && (tempNums[(cnt - 1) % 3] >= tempNums[(cnt - 2) % 3]);++cnt){ tempNums[cnt % 3] = tempNums[(cnt + 1) % 3] + tempNums[(cnt + 2) % 3]; } fib = tempNums[(num - 1) % 3]; //Transfer the answer to permanent variable. -1 to account for the offset of starting at 0 + return fib; } @@ -321,6 +327,35 @@ mpz_class getMpzFib(uint64_t num){ } #endif //NEEDGMP +//This function returns a vector that includes all Fibonacci numbers <= num +template +std::vector getAllFib(const T num){ + std::vector fibList; + //Make sure the number is within bounds + if(num <= 1){ + fibList.push_back(1); + return fibList; + } + else{ //Make sure to add the first 2 elements + fibList.push_back(1); + fibList.push_back(1); + } + + //Setup the variables + T fib = 0; + T tempNums[3]; + tempNums[0] = tempNums[1] = 1; + + //Do the calculation and add each number to the vector + for(T cnt = 2;(tempNums[(cnt - 1) % 3] < num) && (tempNums[(cnt - 1) % 3] >= tempNums[(cnt - 2) % 3]);++cnt){ + tempNums[cnt % 3] = tempNums[(cnt + 1) % 3] + tempNums[(cnt + 2) % 3]; + fibList.push_back(tempNums[cnt % 3]); + } + + //Return the vector that contains all of the Fibonacci numbers + return fibList; +} + //This is a function that performs a bubble sort on a vector template bool bubbleSort(std::vector nums){