Cubic permutations

The cube, 41063625 (3453), can be permuted to produce two other cubes: 56623104 (3843) and 66430125 (4053). 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.


Idea

The key to this problem is to avoid using real permutation, since a 8-digits number will generate $ 8! = 40320 $ permutations, which will signicantly increase search space.

The solution is to use a hash-table to record cubes, with sorted digits as the key.


In [1]:
import sys, os; sys.path.append(os.path.abspath('..'))
from timer import timethis
from collections import defaultdict
In [2]:
def generate_candidates(start):
    i = start
    while True:
        i += 1
        c = pow(i, 3)
        yield c
In [3]:
@timethis
def solve(permutation_cnt):
    cached_cubes = defaultdict(list)
    for c in generate_candidates(100):
        digits = tuple(sorted(map(int, str(c))))
        cached_cubes[digits].append(c)
        if len(cached_cubes[digits]) == permutation_cnt:
            return min(cached_cubes[digits])
In [4]:
solve(3)
Run for 0.006 seconds
Out[4]:
41063625
In [5]:
solve(5)
Run for 0.068 seconds
Out[5]:
127035954683