14 Apr PMCA Saturday 18:30 Python Homework 22.04.09.
Question 1:
The hailstone sequence starting at a positive integer n
is generated by following two simple rules. If n
is even, the next number in the sequence is n/2
. If n
is odd, the next number in the sequence is 3*n+1
. Repeating this process, we generate the hailstone sequence. Write a recursive function hailstone(n)
which prints the hailstone sequence beginning at n
. Stop when the sequence reaches the number 1
(since otherwise, we would loop forever 1, 4, 2, 1, 4, 2, …)
For example, when n=5
, your program should output the following sequence:
5 16 8 4 2 1
Question 2:
Use recursion to write a function multisplit
that consumes two positive integers total
and split
and produces the number of times total
is repeatedly divided into split
even pieces before each piece is of size at most 1.
For example, the value returned by multisplit(8, 2)
will be 3, since 8 can be split into 2 pieces of size 4, which are then each split into 2 pieces of size 2, which are then each split into 2 pieces of size 1 (at which point no further splitting takes place since the pieces are of size at most 1). The value returned by multisplit(8, 3)
will be 2, since 8 can be split into 3 pieces of size 8/3, which are then each split into 3 pieces of size 8/9 (at which point no further splitting takes place since the pieces are of size at most 1).
Sorry, the comment form is closed at this time.