Computer Science Canada factorial and fibonacci functions |
Author: | CodeMonkey2000 [ Mon Aug 07, 2006 9:27 pm ] | ||||||||
Post subject: | factorial and fibonacci functions | ||||||||
this program shows how factorials can be done within a function, by using recursive functions. this code out puts the factorials of 1-10. this is what the function factorial does if the argument is 5:
another recursive function. this time it does fibonacci. the fibonacci series. 0,1,1,2,3,5,8,13,21... it begins with 0 and 1 and has the property that each subsequebt fibonacci number is the sum of the previous two fibonacci numbers. 0 0 1 1 2 1 3 2 4 3 5 5 6 8 7 13 8 21 n ??? this program basiclly finds the Nth fibonacci heres how the function works (very roughly) with the 3rd fabonici(sp i know)
|
Author: | Cervantes [ Mon Aug 07, 2006 9:55 pm ] | ||||||||
Post subject: | |||||||||
Good stuff. That's the basic recursion solution to these problems. But you can optimize it a lot. Consider only your factorial program. The same concepts will apply to the Fib numbers. The following loop is very inefficient:
It is inefficient because to get 4! you multiply 1*2*3*4. To get 5!, all you should need is 5*4!, as your little description says. We've already calculated 4! from the previous loop. But with this code, your function will do all that multiplication again. The solution is to memorize what 4! was when it comes time to calculate 5!. Create an array of factorials. When you need to get a factorial that isn't in your array, expand that array (using the previous elements in that array) until you've expanded it far enough and can answer the initial question (what is the factorial of x, where x is some number larger than the upper() of your array of factorials?). Actually, I just did this in Ruby for a Project Euler question. Here's the code:
A handle preceeded by "@@" is a class variable. This little code snippet allows us to write things like,
and it will be calculated. Then if we were to say
Nothing new would be calculated, because it's already been memoized. P.S. Dan, syntax highlighting has a minor bug. If your code contains a "[i ]" (minus space) then italics will be screwed up in the text afterwards. You won't get any italics until a [/i] is found. After that [/i], the size of the text appears larger, as it does in this post. |
Author: | Catalyst [ Wed Aug 09, 2006 11:36 am ] | ||
Post subject: | |||
fibonacci doesnt require recursion
|
Author: | Clayton [ Wed Aug 09, 2006 2:08 pm ] |
Post subject: | |
OMG its Catalyst :O hes back!!! YAY all hail Catalyst |