Skip to content

Instantly share code, notes, and snippets.

@adilakhter
Last active December 13, 2015 23:28
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 adilakhter/4991558 to your computer and use it in GitHub Desktop.
Save adilakhter/4991558 to your computer and use it in GitHub Desktop.
let max = 1000001L
let memo = Array.create (max|>int) 0L
// Computes Collatz sequence length, given a
// positive integer, x.
let rec collatzSeqLength (x:int64):int64 =
let rec seqLength' (n:int64) contd =
match n with
| 1L -> contd 1L // initalizing sequence length with 1
| _ ->
if n < max && memo.[n|>int] <> 0L then
contd memo.[n|>int]
else
seqLength' (nextCollatz n) (fun x ->
let x' = x+1L //incrementing length and storing it in memo.
if n<max then
memo.[n|>int] <- x'
else
()
contd x'
)
x|>(fun i -> seqLength' i id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment