Nice examples! With a few tricks, I made the Racket program x5 faster. I think you tried to use the simplest program, so I tried to add as few cheats as possible. I added a happy path for fixnums and keep the slow path in case the iterations gets too big:
(define (count-collatz n [cnt 1])
(if (fixnum? n)
(cond
[(= n 1) cnt]
#;[(zero? (unsafe-fxremainder n 2)) (count-collatz (unsafe-fxquotient n 2) (+ 1 cnt))]
[(zero? (fxand n 1)) (count-collatz (unsafe-fxquotient n 2) (+ 1 cnt))]
[else (count-collatz (+ (* 3 n) 1) (+ 1 cnt))])
(cond
[(= n 1) cnt]
[(even? n) (count-collatz (/ n 2) (+ 1 cnt))]
[else (count-collatz (+ (* 3 n) 1) (+ 1 cnt))])))
My program has two versions, the version with `fxand` is slightly faster than the versions with `fxremainder`. I have to used two `unsafe-` functions, but a smart enough optimizer should have fixed them. So I'm adding this example to my wishlist.
I think it would be very hard for the optimizer would be to replace `/` with `quotient`, but the rest look possible.
I think it would be very hard for the optimizer would be to replace `/` with `quotient`, but the rest look possible.