

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
Material Type: Exam; Class: Computation for the Sciences; Subject: Computer Science; University: Wellesley College; Term: Unknown 1989;
Typology: Exams
1 / 3
This page cannot be seen from the preview
Don't miss anything!
Department of Computer Science Wellesley College
Blowing a gasket
Classic recursive examples
Recursion 20-
Recursion
Recursion 20-
Factorial
function result = fact (n) if (n <= 1) % base case
result = 1; else % recursive step
result = n * fact(n-1); end
Recursion 20-
The recursive leap of faith
To solve a problem recursively:
If it is simple enough then solve it immediately Otherwise express solution in terms of smaller, similar problem(s)
Initially this will take some faith on your part
Recursion 20-
Fibonacci numbers, or multiplying rabbits?
Fibonacci numbers first appear around 500 B.C. in writings of a Sanscrit grammarian named Pingala who studied rhythm in language
Leonardo Fibonacci studied these numbers around 1200 in the context of multiplying rabbits
Recursion 20-
Fibonacci function
function result = fibonacci (n) if (n <= 2) % base case result = 1; else % recursive step result = fibonacci(n-1) + fibonacci(n-2); end
fib(5)
fib(4) fib(3)
Recursion 20-
Towers of Hanoi
Recursion 20-
A natural recursive solution
function towersOfHanoi (n, source, destination, spare) if (n == 1) % base case disp(['move disk 1 from ' source ' to ' destination]); else % recursive step towersOfHanoi(n-1, source, spare, destination); disp(['move disk ' num2str(n) ' from ' source ' to ' destination]); towersOfHanoi(n-1, spare, destination, source); end