0

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.

2
  • 3
    The 200th fibonacci number is 453973694165307953197296969697410619233826, around 2^138. The largest number that the C++ standard library provides is a uint64_t, or 2^64. If you want to handle larger numbers, you need an arbitrary precision library such as libgmp. Commented Sep 6, 2019 at 7:33
  • 3
    FYI, since the only operation you use is addition, it's very easy to implement large numbers yourself (as vector<int>). No need to reinvent the wheel, but, 1) it may be a useful experience; 2) if it's an assignment, implementing large numbers may be a part of it. Commented Sep 6, 2019 at 7:42

3 Answers 3

1

The 200th Fibonacci number (and even the 50th) is larger that 2^32 (the int limit). I suggest you to use unsigned long long instead of int, or even create a big integer type using arrays , like here.

Sign up to request clarification or add additional context in comments.

1 Comment

20th or 200th is a big difference
1

Before you adding up the two numbers (in iterative x, y and in recursive the method's return values) which should be checked, whether the addition may cause integer overflow or not. For more info kindly check this post. It may helps you to figure it out.

Comments

0
#include<boost/multiprecision/cpp_int.hpp>

using namespace boost:: multiprecision;

 // just add these two lines , now you can use big int type of size 2^1024

//Declaration as same as normal int

int1024_t  X=0; // can holds values upto 2^1024

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.