Issue
Hello, everyone. My current university assignment is to represent href="https://en.wikipedia.org/wiki/Horner%27s_method" rel="nofollow noreferrer">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
Solution
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);
}
Answered By - Alexander Ivanchenko
Answer Checked By - Candace Johnson (JavaFixing Volunteer)