Last active
December 31, 2018 03:06
-
-
Save kirkins/c8ed6f5746af0c5d1213869c7a905a81 to your computer and use it in GitHub Desktop.
Notes for SICP problems in ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def fibonacci(n) | |
fib_iter(1, 0, n) | |
end | |
def fib_iter(a, b, n) | |
n == 0 ? b : fib_iter((a+b), a, (n-1)) | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def fibonacci(n) | |
n <= 1 ? n : fibonacci( n - 1 ) + fibonacci( n - 2 ) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fibonacci SICP
Above is recursive and inefficient:
The faster version in lisp is:
This is iterative rather than recursive.
Each cycle inputs are shifted, and the last number is decremented for example:
fib-iter 1 0 5
fib-iter 1 1 4
;; First variable is sum of first 2 variables abovefib-iter 2 1 3
;; Last variable is simply decremented by 1 each timefib-iter 3 2 2
;; First variable above is always shifted right,a
becomesb
fib-iter 5 3 1
fib-iter 8 5 0
;; Here 5 is returnedLinks
https://web.archive.org/web/20171120112547/https://mitpress.mit.edu/sicp/full-text/sicp/book/node16.html