CS 201: Collatz

See collatz.rkt

The Collatz Function

In [1]:
(define (collatz n)
  (if (= (modulo n 2) 0) (/ n 2)
      (+ 1 (* n 3))))

Let's try it out.

In [2]:
(collatz 11)
Out[2]:
34
In [3]:
(collatz 34)
Out[3]:
17
In [4]:
(collatz 17)
Out[4]:
52

Recursion

We can have collatz call its own result.

In [5]:
(collatz (collatz (collatz 11)))
Out[5]:
52

Having a function call itself is known as recursion. We can generate the series based on Collatz using recursion.

The function c-series calls itself until the result converges to 1. The function uses let to introduce a local variable next

In [8]:
(define (c-series n)
  (print n)
  (newline)
  (if (equal? n 1) 'done
      (let ((next (collatz n)))
    (c-series next))))
In [9]:
(c-series 11)
11
34
17
52
26
13
40
20
10
5
16
8
4
2
1
Out[9]:
'done

We can generate the series based on Collatz using recursion as above, but without the temporary variable next

In [10]:
(define (c-series2 n)
  (print n)
  (newline)
  (if (equal? n 1) 'done
      (c-series2 (collatz n))))
In [11]:
(c-series2 11)
11
34
17
52
26
13
40
20
10
5
16
8
4
2
1
Out[11]:
'done

Trace

We can trace the execution of the recursive functions using the trace function, which prints out each call to the given function.

When writing recursive code, you will often find it useful to use trace to see what is going on underneath the hood.

In [12]:
(require racket/trace)
In [13]:
(trace c-series)
In [16]:
(c-series 11)
>(c-series 11)
11
>(c-series 34)
34
>(c-series 17)
17
>(c-series 52)
52
>(c-series 26)
26
>(c-series 13)
13
>(c-series 40)
40
>(c-series 20)
20
>(c-series 10)
10
>(c-series 5)
5
>(c-series 16)
16
>(c-series 8)
8
>(c-series 4)
4
>(c-series 2)
2
>(c-series 1)
1
<'done
Out[16]:
'done

End of Collatz notebook.