Skip to content

Instantly share code, notes, and snippets.

@lindig
Last active December 29, 2015 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lindig/7722926 to your computer and use it in GitHub Desktop.
Save lindig/7722926 to your computer and use it in GitHub Desktop.
Diskussion on Hacker News about finding the longest Collatz (-like) sequence. The discussion compared a Haskell implementation with an implementation in C. This adds just another implementation.
(* Discussion on Hacker News: https://news.ycombinator.com/item?id=6822901
*)
exception Error of string
let (@@) f x = f x
let error fmt = Printf.kprintf (fun msg -> raise (Error msg)) fmt
type result = int * int
let max: result -> result -> result = fun (a, x) (b, y) ->
if x > y then (a, x) else (b, y)
let next a = if a mod 2 = 0 then a/2 else (3*a+1)/2
let runlength start =
let rec loop len a =
if a = 1 then
(start, len)
else
loop (len+1) (next a)
in
loop 0 start
let collatz limit =
let rec loop start longest =
if start >= limit
then longest
else loop (start+1) (max longest @@ runlength start)
in
loop 1 (0,0)
let report: result -> unit
= fun (start, len) -> Printf.printf "start: %d length: %d\n" start len
let main () =
let argv = List.tl @@ Array.to_list Sys.argv in
let a2i n = try int_of_string n
with Failure _ -> error "expected a number, found %s" n in
match argv with
| [] -> report @@ collatz 10000
| [n] -> report @@ collatz @@ a2i n
| _ -> error "usage: collatz [n]"
let () =
try
main (); exit 0
with
| Error msg -> Printf.eprintf "Error: %s\n" msg; exit 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment