Hello, everyone. My current university assignment is to represent Horner's method using recursion. Before this task we had to do it with a loop, which was easy. But I have no idea how to do this using recursion with only 2 parameters which cannot be changed.
public static double evalHornerRec(double[] a, double x)
This is the function i have to use
private static int horner(int a[], int x, int n){
int h;
if(n>0)
h=horner(a, x, n-1);
else
return a[n];
return h*x a[n];
}
I found something like this but it has 3 parameters and not 2
CodePudding user response:
As I said in the comment, keep chopping the head off the poly array and pass the chopped version down the recursion call, like so (this may help):
public class Main {
static int horner(int a[], int x) {
switch (a.length) {
case 1: return a[0];
default: return a[0] x * horner(Arrays.copyOfRange(a, 1, a.length), x);
}
}
public static void main(String[] args) {
// 2x^3 - 6x^2 2x - 1 for x = 3 => 5
int[] poly = {-1, 2, -6, 2};
System.out.println(horner(poly, 3)); // 5
}
}
CodePudding user response:
In order to use two-args method, you can call the method containing the actual recursive logic, providing the 0
(the first index of the given array) as the third argument.
Note that the base case of the recursion is when we're hitting the last element an, i.e. when index n
is equal to a.length - 1
.
Otherwise, the call should be handled by the recursive case, containing the logic compliant with the Horner's rule.
public static double evalHornerRec(double[] a, double x) {
return horner(a, x, 0);
}
private static double horner(double a[], double x, int n) {
if (n == a.length - 1) return a[n];
return a[n] x * horner(a, x, n 1);
}