Help Recursion

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

  1. MaxMouse

    MaxMouse New Member

    Joined:
    Jun 7, 2003
    Messages:
    197
    Likes Received:
    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. zabuni

    zabuni New Member

    Joined:
    Jan 2, 2005
    Messages:
    64
    Likes Received:
    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. MaxMouse

    MaxMouse New Member

    Joined:
    Jun 7, 2003
    Messages:
    197
    Likes Received:
    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?
     
  4. korrupshun

    korrupshun New Member

    Joined:
    Sep 8, 2004
    Messages:
    389
    Likes Received:
    0
    Location:
    YourMommasHouse
    that would be correct, when start == stop, the power function is called, essentially squaring stop then returning to the prior call and so on back to the original function call
     

Share This Page