# Help Recursion

Discussion in 'OT Technology' started by MaxMouse, Feb 4, 2005.

1. ### MaxMouseNew Member

Joined:
Jun 7, 2003
Messages:
197
0
Location:
toronto
How would I write a method in Java that counts the sum of squares of the numbers in between two numbers inclusive without using a loop?

So far I have it working for only three numbers, but I don't know how to do it if I don't know the size of the range of the numbers.

2. ### zabuniNew Member

Joined:
Jan 2, 2005
Messages:
64
0
int sumOfSquares(int start, int stop)
{
if (start == stop) return Math.pow(start, 2);
else return Math.pow(start, 2) + sumOfSquare(start+1, stop);
}

That should add all the sums between the start and the stop, stopping once start is equal to stop.

Here's what the calls should look like
sumOfSquares(3,6)
3^2 + sumOfSquares(4,6)
3^2 + 4^2 + sumOfSquare(5,6)
3^2 + 4^2 + 5^2 + sumOfSquare(6,6)
3^2 + 4^2 + 5^2 + 6^2 (End case)

3. ### MaxMouseNew Member

Joined:
Jun 7, 2003
Messages:
197
0
Location:
toronto
Thanks.

I'd just like to know how 'stop' is getting squared. Is it because 'start' is being increased by one, and when start equals stop the if statement is evaluated?

Joined:
Sep 8, 2004
Messages:
389