mirror of
https://bitbucket.org/Mattrixwv/my-classes.git
synced 2025-12-06 18:23:57 -05:00
Added algorithms for finding a Fibonacci number
This commit is contained in:
@@ -11,6 +11,7 @@
|
||||
#include <cinttypes>
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
#include <gmp.h> //This is necessary for the getFib function for numbers larger than a normal int can hold. It can be commented out if needed
|
||||
|
||||
namespace mee{
|
||||
|
||||
@@ -33,6 +34,9 @@ bool isFound(T num, std::vector<T> list);
|
||||
//It is meant to have only the string passed into it from the calling function. num is used for recursion purposes
|
||||
//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);
|
||||
void getFib(mpz_t fibNum, uint64_t num);
|
||||
|
||||
|
||||
template<class T>
|
||||
@@ -143,6 +147,62 @@ std::vector<std::string> getPermutations(std::string master, int num){
|
||||
return perms;
|
||||
}
|
||||
|
||||
uint64_t getFib(uint64_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];
|
||||
tempNums[0] = tempNums[2] = 1;
|
||||
|
||||
//Do the calculation
|
||||
uint64_t cnt = 2;
|
||||
uint64_t location = 1;
|
||||
while(cnt < num){
|
||||
tempNums[location] = tempNums[(location + 1) % 3] + tempNums[(location + 2) % 3];
|
||||
location = (location + 1) % 3;
|
||||
++cnt;
|
||||
}
|
||||
fib = tempNums[(num + 1) % 3]; //Transfer the answer to permanent variable
|
||||
return fib;
|
||||
}
|
||||
|
||||
void getFib(mpz_t fibNum, uint64_t num){
|
||||
//Make sure the number is within bounds
|
||||
if(num <= 0){
|
||||
mpz_set_ui(fibNum, 0);
|
||||
return;
|
||||
}
|
||||
else if(num <= 2){
|
||||
mpz_set_ui(fibNum, 1);
|
||||
return;
|
||||
}
|
||||
mpz_t tempNums[3];
|
||||
//Initialize the variables
|
||||
mpz_init(tempNums[0]);
|
||||
mpz_init(tempNums[1]);
|
||||
mpz_init(tempNums[2]);
|
||||
//Set the variables correctly
|
||||
mpz_set_ui(tempNums[0], 1);
|
||||
mpz_set_ui(tempNums[2], 1);
|
||||
|
||||
//Do the calculation
|
||||
uint64_t cnt = 2;
|
||||
uint64_t location = 1;
|
||||
while(cnt < num){
|
||||
mpz_add(tempNums[location], tempNums[(location + 1) % 3], tempNums[(location + 2) % 3]);
|
||||
location = (location + 1) % 3;
|
||||
++cnt;
|
||||
}
|
||||
mpz_set(fibNum, tempNums[(num + 1) % 3]); //Transfer the answer to the permanent variable
|
||||
|
||||
//Clear the variables
|
||||
mpz_clear(tempNums[0]);
|
||||
mpz_clear(tempNums[1]);
|
||||
mpz_clear(tempNums[2]);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user