Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fibonacci series

I am trying to do an exercise with the Fibonacci series. I have to implement with a recursive function, a succession of the prime n number of Fibonacci and print them in the same function. The problem is that my function print also the intermediate number. The results, for example, for n = 6, should be : 1 1 2 3 5 8. Any solutions?

Thanks

#include<iostream>
using namespace std;
int rec(int n)
{
    int a, b;
    if (n == 0 || n == 1)
    {
        return n;
    }
    else
    {
        a = rec(n - 1);
        b = rec(n - 2);
        cout << a + b << endl;
        return a + b;
    }

}
int main()
{ 
    int n = 6;
    rec(n);
    return 0;
}
like image 979
gerton Avatar asked Mar 25 '26 13:03

gerton


2 Answers

I have taken help of static int. That worked the way you wanted.

void rec(int n)
{
    static int a=0,b=1,sum;
    if(n>0)
    {
         sum = a+b;
         a=b;
         b= sum;
         cout<<sum<<" ";
         rec(n-1);
    }
}

Though you have to print the first Fibonacci number yourself in main().

cout<<"0 ";
rec(n);
like image 121
user2736738 Avatar answered Mar 28 '26 04:03

user2736738


You can use this:

#include<iostream>
using namespace std;
#define MAXN 100
int visited[MAXN];
int rec(int n)
{
    if(visited[n])
    {
        return visited[n];
    }
    int a, b;
    if (n == 0|| n==1)
    {
        return n;
    }
    else
    {
        a = rec(n - 1);
        b = rec(n - 2);
        cout << " " <<a + b;
        return visited[n] = a + b;
    }

}
int main()
{
    int n = 6;
    cout<< "1";
    rec(n);
    cout<<endl;
    return 0;
}

This implementation uses dynamic programming. So it reduces the computation time :)

like image 24
Ali Akber Avatar answered Mar 28 '26 06:03

Ali Akber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!