Added getAllFib function to return a vector of Fibonacci numbers

This commit is contained in:
Matthew Ellison
2019-02-08 15:34:20 -05:00
parent e86278f050
commit 0bec0ff5ab

View File

@@ -64,12 +64,16 @@ bool isFound(T num, std::vector<T> list);
//It can however be used with num if you want the first num characters to be stationary
std::vector<std::string> getPermutations(std::string master, int num = 0);
//These functions return the numth Fibonacci number
uint64_t getFib(uint64_t num);
template <class T>
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<class T>
std::vector<T> getAllFib(const T num);
//This is a function that performs a bubble sort on a vector
template<class T>
bool bubbleSort(std::vector<T> nums);
@@ -277,21 +281,23 @@ std::vector<std::string> getPermutations(std::string master, int num){
return perms;
}
uint64_t getFib(uint64_t num){
template <class T>
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<class T>
std::vector<T> getAllFib(const T num){
std::vector<T> 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<class T>
bool bubbleSort(std::vector<T> nums){