C + + seeking FIB sequence _c language

Source: Internet
Author: User
Tags int size

1. The first version of the 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. The second version

BOOL Fib (int pos, int &elem)
  {
    if (pos < 0 | | pos > 1024)
    {
      elem = 0;
      return false;
    }
    Elem = 1; Note: The definition can only be 1 times
    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. Third version of the 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 this should be called back, this is not clear, leave a mark.

This last version avoids repeated operations and uses a local static object.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.