Don't like ads? PRO users don't see any ads ;-)

# Untitled

By: a guest on Aug 12th, 2012  |  syntax: None  |  size: 1.30 KB  |  hits: 7  |  expires: Never
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
1. How to convert an iterative algorithm to recursive solution
2. double A;
3. int B;
4. double previous=1;
6.
7. double equation(double A,int B){
8.  for(int i=1; i<=B; i++){
10.   previous = answer;
11.  };
13. }
14.
15. equation(A, B) =
16.     IF(B = 1)
17.         A/(1+A)
18.     ELSE
19.         (A*equation(B-1)) / (B+A*equation(B-1))
20.
21. Equation A , B = Equation_internal( A, B , 1, 1)
22.
23.
24. Equation_internal (A , B , i , prev ) =
25.   case i <= B   : return  Equation_internal ( A , B , i+1 , (A* prev )/(i+A*prev) )
26.   otherwise return prev.
27.
28. double equation(double A,int B);
29. double equation2(double A,int B, int curcount, double previous);
30.
31.
32. double A;
33. int B;
34. double previous=1;
36.
37. int main (int argc, const char * argv[])
38. {
39.
40.
41.    double toto= equation(5,3);
42.
43.    double toto2= equation2(5,3,0,1);
44.
45.
46.     return 0;
47. }
48.
49. double equation(double A,int B){
50.     for(int i=1; i<=B; i++){
51.         previous= (A*previous)/(i+A*previous);
52.     };
53.     return previous;
54. }
55.
56. double equation2(double A,int B, int curcount, double previous){
57.
58.     if (curcount == B) {
59.         return previous;
60.     }else{
61.         curcount++;
62.         previous= (A*previous)/(curcount+A*previous);
63.
64.         return equation2(A,B,curcount,previous);
65.     }
66.
67. }