Fibonacci Series w/Templating technique

Alex Edwards 0 Tallied Votes 103 Views Share

Nothing too special, but it was an interesting task.

#include <cstdlib>
#include <iostream>
#include <vector>
#define VALUE_ 12
using namespace std;

/**
Fibonacci series using template recursion -- successful
*/

class Fibonacci{
     private:
             vector<bool> analyzed;
             bool start;
             unsigned short current, firstN;

     public:
            Fibonacci(): analyzed(0), current(0), start(false) {};
            template<unsigned short N>
            inline unsigned short series(){
                if(!start){
                     start = true;
                     vector<bool> tempVector(N, false);
                      analyzed = tempVector;
                     (firstN = N);
                }
                if(analyzed[N] == false){
                    analyzed[N] = true;
                    if((this->series<N>() <= firstN)){
                        cout << (this->series<N>()) << " " << flush;
                    }
                }
                if(N%2 == 0)
                       return(this->series<N - 2>() + ((this->series<N - 1>())));
                else return (this->series<N - 1>() + ((this->series<N - 2>())));
            }

            static void reset(Fibonacci &fib){
                   fib.start = false;
            }
};

template<>
inline unsigned short Fibonacci::series<1>(){
    if(analyzed[1] == false){
          analyzed[1] = true;
          cout << 1 << " " << flush;
    }
    return 1;
};

template<>
inline unsigned short Fibonacci::series<0>(){
    if(analyzed[0] == false){
          analyzed[0] = true;
          cout << 0 << " " << flush;
    }
    return 0;
};

#ifdef NUM
#undef NUM
#define NUM VALUE_
#else
#define NUM VALUE_
#endif

int main(int argc, char *argv[]){
    Fibonacci fib;
    fib.series<NUM>(); //prints out the entire series up to N
    Fibonacci::reset(fib);
    cout << endl;
    fib.series<NUM - 6>();
    cin.get();

#undef NUM
#undef VALUE_

    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.