177k views
4 votes
Rewrite the following iterative method as a recursive method that computes the same thing. Note: Your recursive method will require an extra parameter.

a) Fibonacci sequence
b) Newton's method
c) Gauss-Seidel method
d) Binary search

1 Answer

5 votes

Final answer:

To rewrite an iterative method as a recursive method, identify the base case(s) and define the recursive case(s). Examples include the Fibonacci sequence, Newton's method, Gauss-Seidel method, and binary search.

Step-by-step explanation:

To rewrite an iterative method as a recursive method:

Identify the base case(s), which are the stopping conditions for the recursion.

Define the recursive case(s), which determine the recursive calls.

Create the recursive function by combining the base case(s) and the recursive case(s).

Implement the necessary parameters for the recursive function.

a) For the Fibonacci sequence, the recursive method can be defined as follows:

public int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}

b) Newton's method is used to find the roots of a function. Here's an example of a recursive implementation:

public double newtonMethod(double x, double guess) {
if (Math.abs(x - guess * guess) <= 0.00001) {
return guess;
}
double nextGuess = (guess + x / guess) / 2;
return newtonMethod(x, nextGuess);
}

c) The Gauss-Seidel method is an iterative method for solving systems of linear equations. It can be transformed into a recursive method by updating the values of the variables in each recursive call:

public void gaussSeidel(double[] x, double[] prevX, double[][] matrix, double[] b, int iterations) {
if (iterations == 0) {
return;
}
for (int i = 0; i < x.length; i++) {
double sum = 0;
for (int j = 0; j < x.length; j++) {
if (j != i) {
sum += matrix[i][j] * x[j];
}
}
x[i] = (b[i] - sum) / matrix[i][i];
}
gaussSeidel(x, prevX, matrix, b, iterations - 1);
}

d) Binary search can also be implemented recursively:

public int binarySearch(int[] array, int target, int low, int high) {
if (low > high) {
return -1;
}
int mid = low + (high - low) / 2;
if (array[mid] == target) {
return mid;
} else if (array[mid] < target) {
return binarySearch(array, target, mid + 1, high);
} else {
return binarySearch(array, target, low, mid - 1);
}
}
User Liqang Liu
by
9.0k points