From aed6b8672caa7f01259b2dc87cb6383444718133 Mon Sep 17 00:00:00 2001 From: Matthew Ellison Date: Wed, 14 Nov 2018 00:12:37 -0500 Subject: [PATCH] Added algorithms for finding a Fibonacci number --- Algorithms.hpp | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/Algorithms.hpp b/Algorithms.hpp index 3dfd1d8..e84711a 100644 --- a/Algorithms.hpp +++ b/Algorithms.hpp @@ -11,6 +11,7 @@ #include #include #include +#include //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 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 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 @@ -143,6 +147,62 @@ std::vector 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]); +} }