Skip to content

Instantly share code, notes, and snippets.

@adilakhter
Last active December 12, 2015 02:18
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/4696993 to your computer and use it in GitHub Desktop.
Save adilakhter/4696993 to your computer and use it in GitHub Desktop.
let max = 1000001L
let memo = Array.create (max|>int) 0L
let rec collatzSeqLength (x:int64):int64 =
let nextCollatz (n:int64) =
if n%2L = 0L then n/2L else 3L*n+1L
let rec seqLength' (n:int64) contd =
match n with
| 1L -> contd n
| _ ->
if n < max && memo.[n|>int] <> 0L then
contd memo.[n|>int]
else
seqLength' (nextCollatz n) (fun x ->
let x' = x+1L
//printf "%d " n
if n<max then
memo.[n|>int] <- x'
else
()
contd x'
)
x|>(fun i -> seqLength' i id)
let maxCollazSeqLength' (x:int64,y:int64) =
let x',y' = System.Math.Min(x,y), System.Math.Max(x,y)
let mutable maxL = 0L
let mutable num = 0
for i=(x'|>int) to (y'|>int) do
let r = collatzSeqLength (i|>int64)
if r>maxL then
maxL <- r
num <- i
else
()
maxL,num
maxCollazSeqLength' (1L, max-1L);;
// result : val it : int64 * int = (525L, 837799)
// 837799 has the maxLength := 525
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment