I used memoization to reduce the time took to complete recursive fibonacci.
But problem is that it cause integer overflow so the numbers are not complted after 50thish number.
so how can i prevent integer overflow both in recursive and iterative?
i have heard that operator overload can solve it..? but i have no clue how to do it.
int recursiveFib(int n) {
if (n <= 1)
return n;
else if (memo[n]!=0)
return memo[n];
else
return memo[n] = recursiveFib(n - 1) + recursiveFib(n - 2);
}
int iterativeFib(int n) {
int x = 0, y = 1, z = 0;
for (int j = 0; j < n; j++) {
z = x + y;
x = y;
y = z;
}
return x;
}
int main() {
for (int n=0; n<=200; n+=10){
cout << "when n equals to " << n << ", Recursive Fibonacci : \n";
for (int i = 0; i <= n; i++) {
cout << recursiveFib(i)<<" ";
}
for (int n = 0; n <= 200; n += 10) {
cout << "when n equals to " << n << ", Iterative Fibonacci : \n";
for (int i = 0; i <= n; i++) {
cout << iterativeFib(i) << " ";
}
}
The result should be printing fibonacci with every increment of n+10, both recursive and iterative in 30 minutes.