I\'m trying to find the sum of the Fibonacci sequence in Java, but the run time is taking way too long (or is it suppose to?). This slows down anytime I use an integer past
For n > 2
, an invocation of your getSum(n)
recursively invokes itself twice. Each of those invocations may recurse further. The total number of method invocations scales as 2^n
, and 2^50
is a very large number. This poor scaling reflects the fact that the simple-minded recursive approach ends up needlessly recomputing the same results (e.g. fib(4)) a great many times, and it is why your program slows down so rapidly as you increase n
.
The negative return value you get after a certain point arises from exceeding the limits of data type int
. You could get a larger limit with a wider data type, presumably long
. If that's not enough then you would need to go to something like BigInteger
, at a substantial performance penalty.