Stack overflow with Fibonacci's recursive call

和自甴很熟 提交于 2019-12-12 22:15:14

问题


How exactly is the Java stack set up?

For university, I shall determine what the biggest possible Fibonacci number that is calculated by a recursive method and can be handled by the stack.

The interesting thing is: Tests showed that it doesn't matter how much -Xmx and -Xms the JVM has. I am able to run up to Fib(4438). But the results aren't consistent. Somtimes it goes down to 4436.

Is there formular for the stack?

Any increase of the stack via -Xss 4096m doesn't make a difference.


回答1:


-Xmx and -Xms sets memory accessible for JVM heap, you need to increase stack size, you do this with the help of -Xss option.




回答2:


You've misinterpreted the assignment. Stack size matters very little. The problem is exponential. And you cannot possibly have gotten to Fib(4438) with the naive recursive program. Using the following code, you'll be lucky if you make it to Fib(50):

public static BigInteger f(int n) {
    if (n == 0) 
        return BigInteger.ZERO; 
    if (n == 1) 
        return BigInteger.ONE; 
    return f(n-1).add(f(n-2));
}



回答3:


Java. How to program, 9th edition, Deitel and Deitel, page 771:

 // Fig. 18.5: FibonacciCalculator.java
 // Recursive Fibonacci method.
 import java.math.BigInteger;
 public class FibonacciCalculator
 {
     private static BigInteger TWO = BigInteger.valueOf( 2 );


     // Recursive declaration of method fibonacci
     public static BigInteger fibonacci( BigInteger number )
     {
         if ( number.equals( BigInteger.ZERO ) ||
              number.equals( BigInteger.ONE ) ) // Base cases
             return number;
         else // Recursion step
             return fibonacci( number.subtract( BigInteger.ONE ) ).add(
         fibonacci( number.subtract( TWO ) ) );
     } // end method fibonacci


     // Displays the Fibonacci values from 0-40
     public static void main( String[] args )
     {
         for ( int counter = 0; counter <= 40; counter++ )
             System.out.printf( "Fibonacci of %d is: %d\n", counter,
         fibonacci( BigInteger.valueOf(counter)));
     } // End main()

 } // end class FibonacciCalculator

I hope this helps.



来源:https://stackoverflow.com/questions/10321088/stack-overflow-with-fibonaccis-recursive-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!