60 Days of Euler in F# - Problem 52

The Problem

It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.

Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.

The Solution

Now that we've passed problem 50, the problems start to get harder. I'm going to skip around a bit. I've gone directly from problem 50 to 52 because I haven't (yet) made my problem 51 solution sufficiently fast. But I'm getting there.

To solve this problem, the first thing we need is a function to determine if n times m contains the same digits as as n.

let checkMultiple (n : int) (ns : string) (m : int) =
    let multiple = (n * m).ToString()
    multiple.Length = ns.Length && 
    (ns |> Seq.forall (fun d -> multiple.IndexOf(d) >= 0))

The checkMultiple function takes a number, a string representation of that number, and a multiplier as input. It multiplies n * m and converts the result to a string. If that string has the same length as ns and contains all the same characters as ns, then we've found a match.

let isAnswer n =
    let ns = n.ToString()
    seq { 2..6 }
    |> Seq.forall (fun m -> checkMultiple n ns m)

The isAnswer function examines an n. If the checkMultiple function returns true for n multiplied by 2..6, then it returns true.

Now we can find the answer.

seq { 1..System.Int32.MaxValue }
|> Seq.find isAnswer
Other Posts in This Series