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
.