Project Euler Problem 62 Solution

Question

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.

Haskell

import Data.List (sort)
import qualified Data.Map as Map

cubes :: Map.Map String [Integer]
cubes = Map.fromListWith (++) [(sort (show cube), [cube]) | x <- [1..10000], let cube = x^3]

main :: IO ()
main = print $ minimum [minimum ns | (_, ns) <- Map.toList cubes, length ns == 5]
$ ghc -O2 -o cubic-permutations cubic-permutations.hs
$ time ./cubic-permutations
real   0m0.044s
user   0m0.035s
sys    0m0.009s

Python

#!/usr/bin/env python
from collections import defaultdict
def cube(x): return x**3

def main():
    cubes = defaultdict(list)
    for i in range(10000):
        c = cube(i)
        digits = ''.join(sorted([d for d in str(c)]))
        cubes[digits].append(c)
    print(min([min(v) for k, v in list(cubes.items()) if len(v) == 5]))

if __name__ == "__main__":
    main()
$ time python3 cube-permutations.py
real   0m0.060s
user   0m0.053s
sys    0m0.008s