Reputation: 121
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
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
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
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:
So, long story short: your whole algorithm is bogus, and you need to step back and rethink what you are doing here!
Upvotes: 3