import java.util.*;

class Euler62 {

    private static class Options {
        int familySize = 5;
        boolean runCheckpoints = true;
    }

    private static boolean parseIntAfterPrefix(String arg, String prefix, Options options) {
        if (!arg.startsWith(prefix)) {
            return false;
        }
        String tail = arg.substring(prefix.length());
        if (tail.isEmpty()) {
            return false;
        }

        int parsed = 0;
        for (int i = 0; i < tail.length(); i++) {
            char c = tail.charAt(i);
            if (c < '0' || c > '9') {
                return false;
            }
            parsed = parsed * 10 + (c - '0');
        }
        options.familySize = parsed;
        return true;
    }

    private static boolean parseArguments(String[] args, Options options) {
        for (String arg : args) {
            if (arg.equals("--skip-checkpoints")) {
                options.runCheckpoints = false;
                continue;
            }
            if (parseIntAfterPrefix(arg, "--family-size=", options)) {
                continue;
            }
            System.err.println("Unknown argument: " + arg);
            return false;
        }
        return options.familySize >= 2;
    }

    private static long solve(int familySize) {
        Map<String, List<Long>> groups = new HashMap<>();
        int currentDigits = 1;

        for (long n = 1; ; ++n) {
            long cube = n * n * n;
            int digits = String.valueOf(cube).length();

            if (digits != currentDigits) {
                long best = -1;
                for (Map.Entry<String, List<Long>> entry : groups.entrySet()) {
                    List<Long> vec = entry.getValue();
                    if (vec.size() == familySize) {
                        long candidate = Collections.min(vec);
                        if (best == -1 || candidate < best) {
                            best = candidate;
                        }
                    }
                }
                if (best != -1) {
                    return best;
                }
                groups.clear();
                currentDigits = digits;
            }

            char[] keyArray = String.valueOf(cube).toCharArray();
            Arrays.sort(keyArray);
            String key = new String(keyArray);
            groups.computeIfAbsent(key, k -> new ArrayList<>()).add(cube);
        }
    }

    private static boolean runCheckpoints() {
        if (solve(3) != 41063625L) {
            System.err.println("Checkpoint failed for family size 3");
            return false;
        }
        return true;
    }

    public static void main(String[] args) {
        Options options = new Options();
        if (!parseArguments(args, options)) {
            System.exit(1);
        }
        if (options.runCheckpoints && !runCheckpoints()) {
            System.exit(2);
        }

        System.out.println(solve(options.familySize));
    }
}
