
Untitled
By: a guest on
Aug 12th, 2012 | syntax:
None | size: 1.30 KB | hits: 7 | expires: Never
How to convert an iterative algorithm to recursive solution
double A;
int B;
double previous=1;
double answer;
double equation(double A,int B){
for(int i=1; i<=B; i++){
answer= (A*previous)/(i+A*previous);
previous = answer;
};
return answer;
}
equation(A, B) =
IF(B = 1)
A/(1+A)
ELSE
(A*equation(B-1)) / (B+A*equation(B-1))
Equation A , B = Equation_internal( A, B , 1, 1)
Equation_internal (A , B , i , prev ) =
case i <= B : return Equation_internal ( A , B , i+1 , (A* prev )/(i+A*prev) )
otherwise return prev.
double equation(double A,int B);
double equation2(double A,int B, int curcount, double previous);
double A;
int B;
double previous=1;
double answer;
int main (int argc, const char * argv[])
{
double toto= equation(5,3);
double toto2= equation2(5,3,0,1);
return 0;
}
double equation(double A,int B){
for(int i=1; i<=B; i++){
previous= (A*previous)/(i+A*previous);
};
return previous;
}
double equation2(double A,int B, int curcount, double previous){
if (curcount == B) {
return previous;
}else{
curcount++;
previous= (A*previous)/(curcount+A*previous);
return equation2(A,B,curcount,previous);
}
}