(in java) // precondition: i <= j // postcondition: The sum i^2 (i 1)^2 (i 2)^2
ID: 3638015 • Letter: #
Question
(in java)// precondition: i <= j
// postcondition: The sum i^2 (i 1)^2 (i 2)^2 ... j^2
// has been returned
public static int sumSquares(int i, int j)
{
// If n = j-i 1 >= 2, the sum of squares is the sum of squares
// of the first half plus the sum of squares of the second
// half. This breaks it into two smaller instances of your
// original problem.
int mid = (i j)/2;
int n = j-i 1;
if(j == i){
return i * j * 2;
}
else{
if (n < 2){
System.out.println("sum " (j * j));
return (j*j);
}
else{
// does not like this call;
return sumSquares(mid, j) sumSquares(i,mid);
}
}
Why does this not work? what is a better recursive case? how can i think through this logically, so that it will be easy for me in the future?
Explanation / Answer
public static int sumSquares(int i, int j) { if (i == j) return i*j; else return (i*i) + sumSquares(i+1, j); } I didn't do exactly the same thing as you did, but this way is simpler but you could probably do it your way using the code above as a base and the problem with your very last return call was you did not include any operations so you tried to return int int which confused your compiler.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.