-1

I want to implement a recursive method that finds the sum of x consecutive integers, starting from a starting number and ending with an end number.

For example, if start = 0 and end = 3, the method returns 6 (0+1+2+3). I tried to come up with the right code but I'm new to recursion and I couldn't find the right base case.

public static int summation(int start, int end) {
        if (start == end) {
            return 0;
        }
        else {
            return  summation(end, end - 1);
        }
}
  • 1
    As you are summing numbers, your recursive case will need to add a number to the result of the recursive call. Also, does it look correct to you that `start` is unused in the recursive case? I suggest that you either run through your code on paper, or use the debugger. – tgdavies Jan 29 '22 at 03:24

2 Answers2

1

This works but make sure that start is less than end.

public static int summation(int start, int end) {
    if(start < end) return start + summation(start + 1, end);
    else return end;
}

If you want to use the method to calculate sum between start and end even if start > end, then use this code:

public static int summation(int start, int end) {
    if(start < end) return start + summation(start + 1, end);
    else if(start > end) {
        start += end;
        end = start - end;
        start -= end;
        return summation(start, end);
    }
    else return end;
}

If recursion is not compulsory, you can use the formula for sum of Arithmetic Progression which you learn in HighSchool Algebra.

Formula for Sum of an AP is
S = n/2 * (2a + (n-1) * d)

In your case as you have to find the sum of consequetive terms, this formula simplifies to:
S = n/2 * (2a + n -1 )

Here, a is the starting term and n is the x consequetive integers from start to end.

public long sum(int start, int end) {
    int n = end - start + 1;
    return n/2 * (2L * start + n - 1);
}

Works even if start and end are negative. Just make sure start < end.

Aditya Arora
  • 204
  • 1
  • 10
0

Recursion is a terrible approach here. Let's apply the method Gauss used in elementary school, the sum of the numbers 1 to n is found by taking of half of n multiplied by n + 1. Like,

private static long sumN(int n) {
    return ((1L + n) * n) / 2;
}

Then you can use that to find summation like

private static long summation(int start, int end) {
    return sumN(end) - sumN(start);
}

No recursion (or iteration) required.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249