1

In my program,user will be asked for 2 different options.

I chose option 2..iterative and key in any value which will then lead to the output.

However,when i choose the 1st option which is recursive,it wont output anything that its value is above 30.Meaning to say,you will see an output if key in a value of 30..& there will be no output if were to key in the value of 40 or 50.

Can anyone please test on your compiler too?Its ok if something wrong with my compiler but if there is something wrong with my code.

#include<iostream>
using namespace std;

/* Fibonacci: recursive version */
int Fibonacci_R(int n)
{
    if (n <= 0) return 0;
    else if (n == 1) return 1;
    else return Fibonacci_R(n - 1) + Fibonacci_R(n - 2);
}

// iterative version
int Fibonacci_I(int n)
{
    int fib[] = { 0, 1, 1 };
    for (int i = 2; i <= n; i++)
    {
        fib[i % 3] = fib[(i - 1) % 3] + fib[(i - 2) % 3];
        cout << "fib(" << i << ") = " << fib[i % 3] << endl;
    }
    return fib[n % 3];
}

int main()
{
    int a, opt;
    cout << "Please choose the available option:\n";
    cout << "1)Recursive\n";
    cout << "2)Iterative\n";
    cin >> opt;
    if (opt == 1)
    {
        cout << "Please input value:\n";
        cin >> a;
        Fibonacci_R(a);
        cout << endl << "From recursive function" << endl;
        for (int i = 1; i <= a; ++i)
            cout << "fib(" << i << ") = " << Fibonacci_R(i) << endl;
        cout << endl;
    }
    else
    if (opt == 2)
    {
        cout << "Please input value:\n";
        cin >> a;
        Fibonacci_I(a);
    }
    system("pause");
    return 0;
}
nishantjr
  • 1,788
  • 1
  • 15
  • 39
  • 14
    time to learn about debugging – keyser Aug 14 '14 at 12:13
  • Use the iterative method with value `50`. Are you certain that the value of `fib(47)` is correct? – tgmath Aug 14 '14 at 12:24
  • 1
    As someone wrote on SO recently: The complexity of the recursive calculation of `fib(n)` is `O(fib(n))`. – tgmath Aug 14 '14 at 12:29
  • 1
    I will not tell why it is stuck. But other things I noticed: 1) the semantics of Fibonacci_R and Fibonacci_I are different. The latter one prints out something, the former does not. This is confusing and ugly. 2) the line with "Please input value:\n" is there twice. Why? If you put it before the main if, you will need it only once. 3) line Fibonacci_R(a) does nothing useful... make the corrections and then debug... – HiFile.app - best file manager Aug 14 '14 at 12:32
  • It's not stuck, it's just taking a very long time, as it repeatedly computes all earlier fibonacci numbers, which your iterative version doesn't. – molbdnilo Aug 14 '14 at 12:50
  • There's a major buffer overflow in `int Fibonacci_I`, too. – MSalters Aug 14 '14 at 14:02

3 Answers3

2

When implementing an algorithm, I like to mentally evaluate the algorithm, to see what the computer is doing.

  fib(30)
= fib(29)  +  fib(28)
= fib(28)  +  fib(27)  +  fib(27)  +  fib(26)
= fib(27)  +  fib(26)  +  fib(26)  +  fib(25)+  fib(26)+  fib(25) +  fib(25)+  fib(24)

I notice that this algorithm seems really really inefficient. To calculate fib(30) it require 2^30 calculations! That's 1073741824!

Even worse, if I increase the number by 1, the time/operations to get a result doubles!

It will probably run forever with a large enough number! (Well until I fall asleep or my CPU burns up atleast)


Optimization

However, I notice that a lot of the calculations are redundant. To calculate fib(30), it must calculate fib(29) and fib(28). To calculate fib(29), it calculates fib(28) again. So inefficient!

When I see these kind of calculations the first thing that springs to mind is a technique call memoization. It caches results from a previous calculation and stores them for later use.

Using that in this case will reduce the number of calculations to something around 60 operations (?) at the cost of using more memory.

Example: What is memoization and how can I use it in Python?

Community
  • 1
  • 1
nishantjr
  • 1,788
  • 1
  • 15
  • 39
0

It is not stuck, it just takes too long. It is because the complexity of recursive calculation. I assume that this school example was meant to show why recursive approach is inferior most of the time and should not be used.

Suppose you want to calculate Fibonacci_R(10). You will need to call Fibonacci_R(8) and Fibonacci_R(9). For calculation of Fibonacci_R(9) you will need to call Fibonacci_R(8) and Fibonacci_R(7). Which means you are calling Fibonacci_R(8) twice. If you continue along you will find that you are calling Fibonacci_R(7) three times - two times for Fibonacci_R(8) and once for Fibonacci_R(9)... you call Fibonacci_R(6) five times - two times for Fibonacci_R(8) and three times for Fibonacci_R(7)... etc. This is really hard when you start not with 10 but with 30. This will make your processor burn if you increase the number even more. Do not try it at home or make sure you have fire extinguisher at hand.

Btw. recursive algorithm is usually inferior not because of the complexity but because of limited memory stack which is used to store the variable and return address when calling a function.

  • 2
    "...recursive approach is inferior..." in this particular example. Recursion is a valid programming technique in several situations. – Alessandro Teruzzi Aug 14 '14 at 13:31
  • Well, I wrote "most of the time" in my answer. If it can be avoided, then it usually is better to avoid it. I agree, sometimes it is better or the only possible way. There is no argument about it. – HiFile.app - best file manager Aug 14 '14 at 15:14
0

A condition needed to be set for "int a" so while true, the "Fibunacci_R" function could execute. So; I used a "do/while" condition/loop at the point where "Fibunacci_R" is called and it worked

#include <iostream>
using namespace std;

/* Fibonacci: recursive version */
int Fibonacci_R(int n)
{
    if (n <= 0) return 0;
    else if (n == 1) return 1;
    else return (Fibonacci_R(n - 1) + Fibonacci_R(n - 2));
}

// iterative version
int Fibonacci_I(int n)
{
    int fib[] = { 0, 1, 1 };
    for (int i = 2; i <= n; i++)
    {
        fib[i % 3] = fib[(i - 1) % 3] + fib[(i - 2) % 3];
        cout << "fib(" << i << ") = " << fib[i % 3] << endl;
    }
    return fib[n % 3];
}

int main() {
    int a, opt;
    cout << "Please choose the available option:\n";
    cout << "1)Recursive\n";
    cout << "2)Iterative\n";
    cin >> opt;
    if (opt == 1) {
        cout << "Please input value:\n";
        cin >> a;

        // Here
        do {
            cout << endl << "From recursive function" << endl;
            for (int i = 1; i <= a; ++i)
                cout << "fib(" << i << ") = " << Fibonacci_R(i) << endl;
            cout << endl;
            break;
        } while (Fibonacci_R(a));
    }
    else
    if (opt == 2)
    {
        cout << "Please input value:\n";
        cin >> a;
        Fibonacci_I(a);
    }
    system("pause");
    return 0;
}

It just takes an awful lot of time to calculate an input of integers greater than 45