简体   繁体   中英

Fixing Exception in thread “main” java.lang.StackOverflowError

What is the reason of the StackOverflowError? I was trying it for a while but still can't get why it happens, and how to fix it.

The formula used in the code is a requirement.

public static long fib(long n){
    if(n == 1 || n == 2)
        return 1;       
    else if(n > 2 && n%2 == 0)//even

        return fib((n/2+1)*(n/2+1)) - fib((n/2-1)*(n/2-1));

    else //odd

        return fib(((n+1)/2)*((n+1)/2)) + fib(((n-1)/2)*((n-1)/2));

}

public static void main(String[] args){

    for(int i = 1; i <= 10; i++)
        System.out.println(fib(i)+" ");

}

Not really sure what you are trying to achieve with your method, but by just adding some System.out.println to your code you can see what you are getting in each recursive call. For what I see your "odd" call is getting into an infinite loop and that is why you got that StackOverflowError error, Typically this is caused when your recursive functions doesn't have the correct termination condition, that is to say, it ends up calling itself forever.

For the way you start your code and the "fib" method name, it looks like you are trying to perform Fibonacci, which can be done in a simpler way:

public static int getFibonacci(int n) {  
if (n == 1) { 
  return 1; 
} 
if (n == 2) { 
  return 1; 
} 
return getFibonacci(n - 1) + getFibonacci(n - 2); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM