CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Apr 2009
    Posts
    1

    Recursive Functions and Fibonacci numbers... (noobie help)

    1st year of college, second semester in, and i think i'm on the verge of failing, so i thought i'd finally join to get some good advice. my teacher is ok, but mostly unclear on how to do certain things. This time, its recursive functions.

    i am suppose to write a recursive function to find the nth Fibonacci number and then find the run-time. this is what i think i'm suppose to do:

    Code:
    long int fib(int n)
    {
    if (n==1 || n==2) return 0;
    else return fib (n-1) + fib(n-2);
    }
    but where do i put the "cin" to enter in the nth term? then at the end i believe im suppose to put:

    Code:
    int main ()
    {
    int start, end, n;
    start=clock();
    cout << #(n);
    end=clock();
    cout << "Run-time- " << (end-start)/1000
    return 0;
    }
    although im not positive on the clock thing. 50 minute lesson on this and i came out not having a clue. hopefully someone can clear thing up for me. Thanks in advance!!

  2. #2
    Join Date
    Nov 2007
    Posts
    613

    Re: Recursive Functions and Fibonacci numbers... (noobie help)

    1. You can place the "cin" right after the declaration of "n".

    2. The first two Fibonacci numbers are both 1, not 0. Otherwise all the Fibonacci numbers will yield 0.

    3. You forgot to call the "fib" function from the "main" function.

    4. To get the time in seconds you must divide by the constant CLOCKS_PER_SEC, not by 1000.

    5. I suspect the timing will yield 0, even for very large values of n. In our days computers are too fast to measure such operations in secons.

    6. Because you're using a recursive function, for very large values of "n" you'll need a huge stack and you may get insufficient memory errors (depending on how much available memory you have).

  3. #3
    Join Date
    Apr 2009
    Posts
    21

    Re: Recursive Functions and Fibonacci numbers... (noobie help)

    Time is so easy.

    Code:
    #include <windows.h>
    
    int startTime, endTime;
    
    startTime = timeGetTime(); // gives you a time in milliseconds
    
    // ...
    
    endTime = timeGetTime() - startTime;
    
    endTime /= 1000; // to convert to seconds

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured