0

I wrote this method that finds the nth term of the fibonacci sequence, and it works perfectly fine if you put in number like 10, but if the number gets bigger for example 100, the console window won't even show up. Does this have to do with the maximum size of an int? Or maybe a problem with the stack size? I don't care about negatives I'll deal with that later. But what is the problem with my code?

public static int fibonacci(int n){
    if(n == 0 || n == 1) return 1;
    return fibonacci(n-2) + fibonacci(n-1);
}
user207421
  • 305,947
  • 44
  • 307
  • 483
Mike
  • 87
  • 10
  • 2
    Yes, integer overflow is a problem, but it does not affect runtime. Calculating fibonacci numbers without a cache is very computationally intensive. http://stackoverflow.com/questions/360748/computational-complexity-of-fibonacci-sequence – Thilo Jan 27 '16 at 00:58
  • 1
    Call stack size is the most significant factor for the run time of this. Look into memoization at this post http://stackoverflow.com/questions/7875380/recursive-fibonacci-memoization – OneCricketeer Jan 27 '16 at 00:58
  • 1
    Recursive Fibonacci evaluation becomes unusably slow somewhere around 45. Use an iterative method, or memorization. – user207421 Jan 27 '16 at 01:01
  • 1
    Or, use the "closed form" to calculate it based on the golden ratio. – Daniel Jan 27 '16 at 01:06
  • Poor title. The title should express something about the problem, not just your helplessness. – user207421 Jan 27 '16 at 01:08

0 Answers0