Java recursive call stack overflow error

Asked 2 years ago, Updated 2 years ago, 141 views

public static void main(String[] args) {
    // // TODO Auto-generated method stub


    int x =2;
    int n =5;
    long result = 0;

    for (int i =0;i<=n;i++){
        result += power(x,i);
    }//end of i
    System.out.println(result);

}//end main
static long power(int x, int n) {
    return (n==1)? x : x*power(x,n-1);
}//end of power

I've solved an example that adds everything from x1 to xn why do I get a stack overflow error when I run it?

1n

if(n==1) return x; return x * power(x,n-1); This part

return (n==1)? x : x*power(x,n-1); I changed it like this.

Please let me know if there is anything wrong!!

java recursive call overflow

2022-09-22 14:59

2 Answers

Don't you think we don't need to implement the power function ourselves?

public static void main(String[] args) {
 long result = 0;
 int x = 2, n = 5;

 for (int i = 1; i <= n; i++) {
  result += pow(x, i);
 }

 System.out.println(result);
}

public static long pow(int x, int n) {
 return (n > 0) ? x * pow(x, n - 1) : 1;
}

You can make it like this.
For reference, in the source you posted, i is a code that repeats from 0 to n, but the power function calls the power function until n becomes 1, so if you call power (x, 0), a recursive call stack overflow error occurs as above.


2022-09-22 14:59

for(int i=0)->for (int i =1)


2022-09-22 14:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.