This is my code for a recursive function written in non-final form, I would like to make it iterative with a while , but I really can't do it, advice to do it with bottom-up? The abc method is a square root(x) , and the number of iterations performed (n) , the higher the iteration the better the result.
public static Double abc(int x,int n){
Double d = .0;
if(n==0){ //caso base
d = 1.0;
}else{
d = (abc(x,n-1)+(x/abc(x,n-1)))/2;
}
return d;
}
This is what I have tried with the while loop:
public static Double abcIter(Integer x,Integer n){
Double res = 1.0;
Double r0=.0;
Integer numeroAuxiliar = 0;
while(numeroAuxiliar<=n){
res = (res+(x/res))/2;
r0 = res;
res = (r0+(x/r0))/2;
numeroAuxiliar++;
}
return res;
}
When I try some root and iteration with the while it doesn't give me the exact value. On the other hand, the first method works well for me. Tips on the while method, and bottom-up?
Any recursive function with tail recursion can be made into an iterative function.
A tail recursive function is one that always ends in
return metodoRecursivo(parametros)
orreturn expresion_sin_llamada_recursiva
.Your function is not tail recursive but can be converted to tail recursive by passing an accumulator parameter (this is the hardest step):
Once we have the function in tail recursive form, the steps are always the same and are done mechanically.
First put a loop
while (true)
around the function:Second, change all recursive calls
abcRecurs( /*parm a*/ a1, /* parm b*/ b1, etc )
to :a=a1; b=b1; etc; continue;
And now you have your iterative function. To finish you can clean it a little. For example
x=x;
, it is useless.And after this you can combine abc and abcRecurs into one :
Try this.