Project Euler 35

To create the rotations I make a “detour” by converting the number into a string and then performing the rotations on the string.


let primes_below v = Euler_utils.primes |> Seq.takeWhile (fun p -> p < v) |> Set.of_seq

let rotate number =
    let number_str = number.ToString()
    let len = number_str.Length - 1
    seq { for i in [ 1..len ] do
              yield int64 (number_str.Substring(i) + number_str.Substring(0,i))

let has_rotated set number =
    let numbers = rotate number
    Seq.forall (fun v -> Set.contains v set) numbers

let find_rotate_numbers number_set = 
    |> Set.filter (fun n -> has_rotated number_set n) 

let rec filter_rotations number_set =
    let numbers = Seq.to_list number_set
    match numbers with
    | head :: tail -> let rotated = rotate head
                      let f_number_set = (Set.remove head number_set) - Set.of_seq rotated 
                      head :: (filter_rotations f_number_set)
    | [] -> []

let values = (find_rotate_numbers (primes_below 1000000L))

values |> Set.iter (fun v -> printfn "Value %A" v )
printfn "Values %A" values

As you might notice, I have included the function filter_rotations which takes only one of each “rotation group”. However, this is not part of the problem and this therefore not used to compute the final answer.