3.11: Exercises
( \newcommand{\kernel}{\mathrm{null}\,}\)
Before you go on, you might want to work on the following exercises.
Years ago I was in a fudge shop and saw a sign that said “Buy one pound of fudge, get another quarter pound free.” That’s simple enough.
But if I ran the fudge shop, I would offer a special deal to anyone who could solve the following problem:
If you buy a pound of fudge, we’ll give you another quarter pound free. And then we’ll give you a quarter of a quarter pound, or one-sixteenth. And then we’ll give you a quarter of that, and so on. How much fudge would you get in total?
Write a script called fudge.m that solves this problem. Hint: start with series.m and generalize it by replacing the ratio 1/2
with a variable, r
.
We have already seen the Fibonacci sequence, F, which is defined recurrently as
for i≥3,Fi=Fi−1+Fi−2
In order to get started, you have to specify the first two elements, but once you have those, you can compute the rest. The most common Fibonacci sequence starts with F1=1 and F2=1.
Write a script called fibonacci2.m that uses a for
loop to compute the first 10 elements of this Fibonacci sequence. As a postcondition, your script should assign the 10th element to ans
.
Now generalize your script so that it computes the nth element for any value of n
, with the precondition that you have to set n
before you run the script. To keep things simple for now, you can assume that n
is greater than 0.
Hint: you’ll have to use two variables to keep track of the previous two elements of the sequence. You might want to call them prev1
and prev2
. Initially, prev1
= F1 and prev2
= F2. At the end of the loop, you’ll have to update prev1
and prev2
; think carefully about the order of the updates!