Project Euler Problem #62!

March 21st, 2010
by Serinox

Problem #62 says:

The cube, 41063625 (345^(3)), can be permuted to produce two other cubes: 56623104 (384^(3)) and 66430125 (405^(3)). In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube.

Find the smallest cube for which exactly five permutations of its digits are cube.

The solution below uses a custom class that takes a int64 in its constructor and to identify it later, it then creates a list of all of the digits of the number sorted by size. We then take an item in the list and see how many times it matches another class in the list including matching against itself. If the items returns 5 then we know its one of the numbers we’re looking for.

Solution in f# and requires FSharp.PowerPack and .Net 4. Runs in ~10 seconds.

#light

open System
open System.Diagnostics
open Microsoft.FSharp.Linq
open Microsoft.FSharp.Collections

type TestCase (y) =
    let num = y
    let icube = (num*num*num).ToString().ToCharArray() |> Seq.sort |> Seq.toList
    member x.Num
        with get() = num
    member x.Cube
        with get() = icube

let watch = new Stopwatch()
watch.Start()

let mutable CheckSet =
    [1000L .. 9000L]
    |> Seq.map (fun x -> new TestCase(x))
    |> Seq.toList

Console.WriteLine("starting check")

let Check (num:TestCase) =
    let count =
        CheckSet
        |> Seq.filter (fun (x:TestCase) -> num.Cube = x.Cube)
        |> Seq.length
    if count = 5 then
        true
    else
        false

let Answer =
    let n =
        CheckSet
        |> PSeq.filter Check
        |> PSeq.toList
    n.[0]

Console.WriteLine(Answer.Num*Answer.Num*Answer.Num)
watch.Stop()
Console.WriteLine(watch.Elapsed)
Console.ReadKey() |> ignore

Tags: , , ,
Posted in Project Euler | Comments (0)

No comments yet

Leave a Reply

You must be logged in to post a comment.