且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java中的Fibonacci序列耗时太长?

更新时间:2022-03-06 00:00:40

n> 2 ,调用 getSum(n)以递归方式调用自身两次。每个调用都可以进一步递归。方法调用的总数按 2 ^ n 进行缩放, 2 ^ 50 是一个非常大的数字。这种不良的缩放反映了这样一个事实:简单的递归方法最终会不必要地重新计算相同的结果(例如fib(4))很多次,这就是为什么你的程序在增加 n

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.

超过数据类型 int的限制后,您获得的负返回值。您可以使用更宽的数据类型获得更大的限制,大概是 long 。如果这还不够,那么你需要去一些类似 BigInteger 的东西,而且会有很大的性能损失。

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.