Recursion is when you can define a function in terms of itself, and often allows you to write very elegant, efficient code.
To get started thinking about recursion, let's consider a basic example: a recursive algorithm to count the number of prime numbers less than or equal to which we'll call For example, since 2, 3, and 5 are all prime.
First, check if is a prime. If so, since there is the prime as well as all of the primes up through If not, then
By the end of this quiz, you'll see how recursion not only creates more elegant code, but also can be used to speed up runtime.
Fill in the recursive step in this function, and then find the answer by evaluating
Hint: Remember the definition of factorials and use it to relate and In the code, you will relate factorial(n)
and factorial(n-1)
.
Recall that the Fibonacci numbers follow the recursion with the initial condition that Fill in recursive step in the code outline provided and use it to calculate
We can now ask ourselves how many arithmetic operations (defined as a single addition, subtraction, multiplication, or division) a recursive implementation requires.
This is easy to calculate for the factorial function. For it, zero operations are required if the input is 1, and an input of requires one more operation than an input of . Inducting, this means that we need operations to compute factorial(n)
.
How many addition operations are required to calculate fibonacci(10)
recursively? You may find the code template helpful in answering this question.
Feel free to play around in the previous problem with the number of operations it takes to calculate various Fibonacci numbers. For example, it takes 102334154 operations to calculate the 40th Fibonacci number.
A good approximation for the number of operations it takes to calculate the th Fibonacci number is which suggests that it would take approximately addition operations to calculate the 1000th Fibonacci number.
Suppose you have a super-computer that can do additions per second (which corresponds to the current state of the art). How long would it take for your super-computer to calculate
This algorithm for calculating the Fibonacci number is prohibitively expensive! This goes to show that even algorithms that look reasonable at first might be really, really bad ideas.
Consider now a different algorithm called smart_fibonacci
. How many additions are necessary to calculate the with smart_fibonacci(1000)
?