C++ find the Fib sequence

  • 2020-05-09 18:52:32
  • OfStack

1. Version 1 program


int fib(int pos)
  {
    int elem = 1;
    int n1 = 1, n2 = 1;
    for (int i = 3; i <= pos; i++)
    {
      elem = n2 + n1;
      n1 = n2;
      n2 = elem;
    }
    return elem;
  }

2. Version 2


bool fib(int pos, int &elem)
  {
    if(pos < 0 || pos > 1024)
    {
      elem = 0;
      return false;
    }
    elem = 1; // Note: definitions can only exist 1 time 
    int n1 = 1, n2 = 1;
    for (int i = 3; i <= pos; i++)
    {
      elem = n2 + n1;
      n1 = n2;
      n2 = elem;
    }
    return true;
  }

Main function call


int main()
  {  
      int pos;
    cout <<"Please enter a position: ";
    cin >> pos;
  
    int elem;
    if(fib(pos, elem))
    {
      cout << "element # " << pos
         << " is " << elem << endl;
    }
    else
      cout << "Sorry. Couldn't calculate element #"
         << pos <<endl;
  }

3. Version 3 improved fib


const vector<int>* fib_new(int size)
  {
    const int max_size = 1024;
    static vector<int> elems;
  
    if(size <= 0 || size >= max_size)
    {
      cerr << "fib_new(): oops:invalid size:"
         << size << "-- can't fulfill request.\n";
      return 0;
    }
    for(int ix = elems.size(); ix < size; ix++)
    {
      if (ix == 0 || ix == 1)
        elems.push_back(1);
      else
        elems.push_back(elems[ix - 1] + elems[ix - 2]);
    }
    return &elems;
  }

Main function call


    const vector<int> *result=fib_new(5);
    cout << result->back();
    
    const vector<int> *result=fib_new(5);
    cout << result->at(4)<< endl;
    // How many times should this call return? I don't know yet, so let me leave a little bit of a mark. 

This last version avoids repetitive operations and USES local static objects.


Related articles: