The following iterative sequence is defined for the set of positive integers:
n –> n/2 (n is even)
n –> 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 –> 40 –> 20 –> 10 –> 5 –> 16 –> 8 –> 4 –> 2 –> 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.
let nextNumber n = if n%2L = 0L then n/2L else 3L*n+1L let findSequenceLength n = let mutable count = 1L let mutable current = n while current > 1L do current <- nextNumber current count <- count + 1L count let longestSeq = [1L..999999L] |> Seq.maxBy findSequenceLength
Having played around with several other approaches, I finally settled down on this solution though I had to use mutable variables in a while loop which is somewhat dissatisfying but it performs quite a bit better than the more functional approach.
As you probably know already, in F# everything is immutable by default and to make a mutable variable you have to mark the variable with the mutable keyword. To assign a value to a mutable variable you need to use the <- operator.
Anyways, the above code is fairly simple, with the findSequenceLength function doing the bulk of the work and returns the number of elements in a sequence using a while loop. It can be equally be written using a more functional (but slower) approach but building the sequence with Seq.unfold and counting the length of the sequence
// the sequence returned by Seq.unfold does not include 1, so for completeness sake, add 1 to the length let findSequenceLength n = Seq.length(Seq.unfold (fun x -> if x = 1L then None else Some(x, nextNumber x)) n) + 1
Subscribe to my newsletter and get new contents delivered straight to your inbox :-)