collatzdr.racket

# Dr. Racket: saving intermidiate results - Collatz Conjecture

I am new into coding and got interested in Dr. Racket and I am facing my first problem now. I created this code:

``````(define (collatz n)
(cond ((= n 1) 1)
((> n 1) (collatz_helper n))))

(define (collatz_helper n)
(if (even? n)
(collatz (/ n 2))
(collatz (+ (* 3 n) 1))))

(collatz 100)    ;; >1
``````

Is it possible to store all the intermidiate results in a list or something and then print them out. I mean by intermidiate results n/2 or 3n+1 until we get 1.

For example n=100 (100, 50, 25, 76, 38, 19, 58, 29, 88, 44, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1)

Can someone give me a clue or show me how to implement something like this?

Solution

• First, you can merge your two functions into one, using `cond` to check all three cases:

``````(define (collatz n)
(cond
((= n 1) 1)
((even? n)
(collatz (/ n 2)))
(else
(collatz (+ (* 3 n) 1)))))
``````

Then, to build the list of intermediate values, you can cons `n` with each recursive step, creating a list whose first element is the original n and last element is 1 (assuming it terminates):

``````(define (collatz n)
(cond
((= n 1) '(1))
((even? n)
(cons n (collatz (/ n 2))))
(else
(cons n (collatz (+ (* 3 n) 1))))))
``````

For example,

``````(collatz 100)
=> '(100 50 25 76 38 19 58 29 88 44 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1)
``````