I've started down the path of optimization through recursion. Adjusting to the new way of thinking is taking a bit of work, but the concepts are beginning to register. Recursion is very useful for replacing loops and giving a more compact and optimized feel to your code. Though the definition of recursion is quite simple (calling a method inside itself until one arrives at a base case and return some value to avoid stack overflow), the actual application could greatly vary however. Recursive sequences like the Fibonnaci Sequence can be expressed recursively as the sum of the previous two numbers F_{n} = f_{n1} + f_{n2} with f_{0} = 0 and f_{1} = 1. Without recursion, one would have to write a method to find the xth number in the fibonacci sequence like this:
Seems like a waste of space to me. I greatly prefer the recursive solution as stated above that F_{n} = F_{n1} + F_{n2} with F_{0} = 0 and F_{1} = 1. With that recursive idea we can write this:
This method saves space and time and looks much better.
public static int fib(int x) { int count = 0; int fib1 = 0; int fib2 = 1; int fibSum; while(count < x) { fibSum = fib1+fib2; fib1 = fib2; fib2 = fibSum; count++; } return fibSum; }
Seems like a waste of space to me. I greatly prefer the recursive solution as stated above that F_{n} = F_{n1} + F_{n2} with F_{0} = 0 and F_{1} = 1. With that recursive idea we can write this:
public static int fib(int x) { if(x <= 1) //this is our base case so we don't get stack overflow { return 1; } return fib(x1)+fib(x1); //remember Fn = Fn1 + Fn2 }
This method saves space and time and looks much better.
0 Comments On This Entry
Trackbacks for this entry [ Trackback URL ]
← November 2020 →
S  M  T  W  T  F  S 

1  2  3  4  5  6  7 
8  9  10  11  12  13  14 
15  16  17  18  19  20  21 
22  23  24  25  26  27  28 
29  30 
Tags
My Blog Links
Recent Entries

Learning Recursion
on Jan 24 2011 09:32 AM
Recent Comments
Search My Blog
0 user(s) viewing
0 Guests
0 member(s)
0 anonymous member(s)
0 member(s)
0 anonymous member(s)