In: Computer Science
Get the file “HW4Part4b.java” from the repository. Modify the program class to match the new file name. Complete it by writing a recursive static int function named recur that is defined as follows: if i ≤ 0 or j ≤ 0, recur(i, j) = 0. if i = j, recur(i, j) = i. if i > j, recur(i, j) = j. In all other cases, recur(i, j) = 2 · recur(i − 1, j) + recur(j − 1, i) Add necessary comments to the program and upload it to your repository.
public class HW4Part4b { | |
public static void main(String[] args) { | |
for (int i = 0; i <= 5; i++) { | |
for (int j = 0; j <= 5; j++) { | |
System.out.println("recur("+i+","+j+") = "+recur(i,j)); | |
} | |
} | |
} | |
public static int recur(int i, int j) { | |
/* replace this comment with your code */ | |
} | |
} |
HW4Part4b
Implemented the recur() method in Java.
The recursive static int function named recur that is defined as follows:
if i ≤ 0 or j ≤ 0, recur(i, j) = 0. if i = j, recur(i, j) = i. if i > j, recur(i, j) = j. In all other cases, recur(i, j) = 2 · recur(i − 1, j) + recur(j − 1, i)
Java Program Code:
public class HW4Part4b
{
//Main Driver function
public static void main(String[] args) {
for (int i = 0; i <= 5; i++) {
for (int j = 0; j <= 5; j++) {
System.out.println("recur("+i+","+j+") = "+recur(i,j));
}
}
}
//recur() method
//params: int i, int j
//returns int
public static int recur(int i, int j) {
//Base step of recur function (termination condition)
if (i <= 0 || j <= 0) {
return 0;
}
else if (i == j) {
return i;
}
else if (i > j) {
return j;
}
//The recurrence relation
else {
return 2 * recur(i-1, j) + recur(j-1, i);
//recursive call
}
}
}
Program Output Screenshot:
Output in text format:
recur(0,0) = 0
recur(0,1) = 0
recur(0,2) = 0
recur(0,3) = 0
recur(0,4) = 0
recur(0,5) = 0
recur(1,0) = 0
recur(1,1) = 1
recur(1,2) = 1
recur(1,3) = 1
recur(1,4) = 1
recur(1,5) = 1
recur(2,0) = 0
recur(2,1) = 1
recur(2,2) = 2
recur(2,3) = 4
recur(2,4) = 4
recur(2,5) = 4
recur(3,0) = 0
recur(3,1) = 1
recur(3,2) = 2
recur(3,3) = 3
recur(3,4) = 11
recur(3,5) = 11
recur(4,0) = 0
recur(4,1) = 1
recur(4,2) = 2
recur(4,3) = 3
recur(4,4) = 4
recur(4,5) = 26
recur(5,0) = 0
recur(5,1) = 1
recur(5,2) = 2
recur(5,3) = 3
recur(5,4) = 4
recur(5,5) = 5