It's running unbelievably slowly. Can you help suggest the way to improve the code in a simple way (simple code, 'coz I'm still at a very beginning level)? Thanks a lot.
Code:
// Exercise 11 - Chapter 5
// Write out the fist so many values of the Fibonacci series
// i.e. 1 1 2 3 5... the next number is the sume of the 2 previous ones
// Find the largest Fibonacci number that fits an int
#include "std_lib_facilities.h"
#include <limits.h>
int Fibonacci (int n)
{
if (n==1||n==2) {
return 1;
}
return Fibonacci(n-1) + Fibonacci(n-2);
}
int main()
{
int n;
cout << "Enter how many values of the Fibonacci series you wish to print out: \n";
cin >> n;
cout << "The first " << n << " values of the Fibonacci series is: \n";
// print the first n values of the Fibonacci series
for (int i=1; i<=n; ++i)
cout << Fibonacci(i) << endl;
// find the largest Fibonacci number that fits in an int
int k = 1;
int count_Fib = 0;
while (Fibonacci(k)<INT_MAX) {
++count_Fib;
++k;
cout << "k = " << k << "\tcount_Fib = " << count_Fib << endl;
}
cout << "Final k = " << k << endl;
cout << "Final count_Fib = " << count_Fib << endl;
cout << "Fibonacci(k) = " << Fibonacci(k) << endl;
cout << "The largest Fibonacci number for an int is " << Fibonacci(count_Fib) << endl;
}