IMBABOT
IMBABOT

Reputation: 121

Recursion with if statements Java

Got two int a and b, need to find the sum of all the numbers between including them too.

Got Recursion Method: with two if statements, if use only one if statement code work fine, otherwise fall with StackOverflowError.

public static int getSum(int a, int b) {
    int result = 0;

    if (a <= 0 && b <= 0)  result = getSum(a + 1, b + 1) + a + b;

    if (a >= 0 && b >= 0)  result = getSum(a - 1, b - 1) + a + b;

    return  result;
}

How can I fix it?

Upvotes: 0

Views: 234

Answers (3)

SomeDude
SomeDude

Reputation: 14228

This doesn't need recursion, but I assume you are trying to learn recursion. Please see comments for explanation.

public static int getSum( int a, int b ) { 
 if ( a == b ) { // if both are equal there are no numbers in between - so sum is number itself.
     return a;
 }
 // if a < b then increment a to reach b otherwise increment b to reach a.
 // this works even if a or b or both are negative.
 // So when you increment a, add 'a' only to current sum and then move forward
 // When you increment b, add 'b' only to current sum and then move forward.
 return a < b ?  a + getSum( a + 1, b ) :  b + getSum( a, b + 1 );    
}

Upvotes: 2

Hongyu Wang
Hongyu Wang

Reputation: 378

You don't need those if statements. Just do it as follows:

public static int getSum(int a, int b){

    if (b < a) return 0;
    if (b == a) return b;
    return a + getSum(a + 1, b);
}

Upvotes: 1

GhostCat
GhostCat

Reputation: 140427

Lets assume a is 1, and b is 2.

if (a <= 0 && b <= 0)  result = getSum(a + 1, b + 1) + a + b;
if (a >= 0 && b >= 0)  result = getSum(a - 1, b - 1) + a + b;

The 2nd kicks in:

result = getSum(1 - 1, 2 - 1) + a + b;

So you call: with a = 0, b = 2. That one picks:

result = getSum(0 + 1, 1 + 1) + a + b;

So you are back to call with 1, 2.

And it starts from scratch. Leading into an endless recursion.

So, there are multiple problems with your current approach:

  • both if conditions might apply. As you use "<=" and ">=", when a or b are 0, both if conditions kick in
  • worse: as shown, your setup allows to easily go down-up-down-up-... forever
  • beyond that: a correct "stop recursion" is missing. For certain input, your code will simply always go and call itself, again.
  • guessing here: you are also missing corner cases, such as a < 0, but b > 0

So, long story short: your whole algorithm is bogus, and you need to step back and rethink what you are doing here!

Upvotes: 3

Related Questions