Well I have been looking for some recursive solution to do the same task, Mostly what people do is, they write a recursive function for finding nth Fibonacci number, and then in the main program, they run a loop n times, and call this recursive function with values 1 to n to get all the n Fibonacci numbers and print them, which is a big overhead.
Here is a solution which does the same task but it calls recursive function only once for getting all up to n Fibonacci numbers, and stores them in an array, and then prints. Which is ((n-1)*(recursive call's overhead)) times faster than the one I mentioned earlier. Thumbs up if you find it helping :)
#include<iostream>
using namespace std;
int *arr;
int iter = 0;
int len;
int returnValue;
void exist(int num, int arr[] ) /* this function checks if the Fibonacci number that recursive function have calcuated is already in the array or not, mean if it is already calculated by some other recursive call*/
{
bool checkExistance = false; /* if this is true, means this Fibonacci number is already calculated and saved in array, so do not save it again*/
returnValue = num;
for (int i = 0; i< len; i++)
{
if(arr[i]==num)
{
checkExistance = true;
break;
}
}
if(!checkExistance)
{
arr[iter]=num;
iter++;
}
}
int fibonacci(int n)
{
if (n==1)
{
exist(1,arr);
return 1;
}
else if (n==2)
{
exist(1,arr);
return 1;
}
else
{
exist((fibonacci(n-1)+fibonacci(n-2)),arr);
return returnValue;
}
}
int main()
{
int n;
cout<<"Enter the number of Fibonacci you want to print: ";
cin>>n;
len = n;
arr = new int[n];
fibonacci(n);
arr[n-1] = 1;
cout<<"1:\t"<<arr[n-1]<<endl;
for (int i = 0; i< len-1; i++)
{
cout<<i+2<<":\t"<<arr[i]<<endl;
}
return 0;
}