Algorithms problem set (3.1- 3.3)
1. Write an algorithm that takes an ordered list and removes repeated elements. For example, if the input is the
list [1,2,4,4,6,7,7,7], then the output would be [1,2,4,6,7].
2. Define a function called collatz() that takes in a positive integer n and returns either 3n+1 if n is odd or n/2 if n is
even. It is a well-known but unproved conjecture that repeated application of this function will eventually lead
to 1 regardless of the input integer. Write an algorithm that takes a positive integer and determine the number
of applications of the collatz() function required to reach 1.
For example, if given the number 12, the algorithm should return 9. If given 27, the algorithm should return 111.
( )
3. Prove that 3x 2 + 2 x − 1 is x 2 .
( )
4. Prove that x 2 x is O 4 x
5. Prove that n n is ( n !) .
6. Sorting functions into “buckets” by growth order
( )
( )
Options: (1) , ( log n ) , ( n ) , ( n log n ) , n 2 , 2n , O ( n !)
For each function, identify which of the above growth orders it belongs to – if any.
a. 3n2 + 4n + 2
b. 2n + log n
c.
log n + 2n
d. 100 2n
e. n25
7. What does it mean for a function to be O(1) ?
What about (1) ?
And what about (1) ?
8. Consider the algorithm below.
procedure find_sums ([a1, a2, …, an]: a list of integers, s: an integer)
1
2
3
4
5
6
locations := []
{This is an empty list.}
for i := 1 to n-1
for j := i+1 to n
if ai + aj = s
Add (append) the ordered pair (i,j) to locations.
return locations
a. List the steps used to evaluate find_sums ([2, 4, 6, 8], 10). What set is returned?
b. Find a function f (n) that counts the number of times the highlighted addition (in line 4) is evaluated when
the algorithm is performed on a list of length n.
( )
c. Prove that f (n) is O n2 .
9. Consider the following algorithm.
procedure reduce (n: a positive integer)
count := 0
while n > 0
count := count + 1
if n is divisible by 3
n := n - 3
else
n := n + 1
return count
a. Record the steps performed when evaluating reduce(14). What value is returned by the algorithm?
b. Find a function f (n) that counts the number of times the highlighted line (count := count + 1) is
executed for a valid input n. Since the number depends on the value of the input, you may either define
the function piece-wise or simply give best-case and worst-case answers.
c. Regardless of best-case or worst-case scenario, what is the “big O estimate” for the runtime complexity
of this algorithm?