MATH 98, Spring 2020 GSI: Andrew Shi
HW 3
Instructions:
• Your submission will consist of three files (and nothing else):
– longest collatz sequence.m – makeScrambler.m
– FPI.m
• Very Important: Create a single compressed (.zip) folder with these files. Name it FirstNameLastNameHW3
•
1 (Collatz Conjecture): The following iterative sequence is defined for the set of positive integers:
n → n/2 (if n is even)
n → 3n + 1 (if n is odd)
As an example, using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Al- though it has not been proven, it is thought that all starting numbers finish at 1 (Collatz Conjecture).
Write a function
function longest starting number = longest collatz sequence(n)
which given an integer n, determines the starting number from 1 to n that produces the longest chain.
Hint: You might want to first write a function collatz that computes the length of the sequence for a given input. Include it as a local function (in other words do NOT submit a separate function for this). If there is a tie choose the smallest starting value.
Source: This question was modified from #14 from Project Euler.
2 (function that creates functions): Write a function
function f = makeScrambler(a, p)
that returns a function f such that
f(x) = xa mod p
MATH 98, Spring 2020 GSI: Andrew Shi HW 3 Note makeScrambler is supposed to return a FUNCTION HANDLE for a given a and p,
not a VALUE.
3 (Fixed Point with Smart Defaults): Write a function
function fixedpt = FPI(f, x0, maxit, tol)
which takes in a function handle f and initial guess x0 and computes a fixed point iteration. maxit is the maximum number of iterations it should perform and tol measures the distance between iterations. Of course, if a fixed point iteration satisfies tol before maxit, it should terminate.
Your code you should have “smart defaults”, meaning if you don’t specify maxit or tol, it should use the default values of maxit = 20 and tol = 1e − 6. To be clear:
f = @(x) sqrt(21/x); x0 = 2;
fixedpt = FPI(f, x0) %Use default maxit and tolerance
fixedpt = FPI(f, x0, 10) %Use maxit = 10 and default tolerance
fixedpt = FPI(f, x0, [], 1e-4) %Use default maxit and tolerance = 1e-4
fixedpt = FPI(f, x0, 10, 1e-4) %Use maxit = 10 and tolerance = 1e-4
These are all 4 possibilities of inputs (listed above). For the first three, you must be able to identify them and figure out how to assign a default maxit/tol, a default tol, and a default maxit, respectively. You will need to use nargin, but that cannot distinguish between the 3rd and the 4th cases since those both have 4 arguments. To do that you must also check whether the third argument isempty.