'Heron Algorithm Recursive C#
I'm trying to implement the heron algorithm recursively in C#. I don't really understand where my code is wrong:
Given definition of algorithm:
x[n+1] = (p-1) /p*x[n] + a/p*x[n]^p-1
Where xo = 1 and p root a
public static double Heron(int x,int p,int a)
{
if(x == 0)
{
return 1.0;
}
return ((p-1.0)/p)*Heron(--x,p,a)+a/(p*Math.Pow(Heron(--x,p,a),--p));
}
e.g Heron(1,3,5) should return 7/3;
Solution 1:[1]
Don't modify the value of x and p in your expression.
Just use
double x_n = Heron(x-1,p,a);
return ((p-1.0)/p)*x_n+a/(p*Math.Pow(x_n,p-1));
I have also kept the value of the recursion in x_n so it does not get called twice.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JAlex |
