from _prime_tools import all_totients


def totient_permutation(ceiling):
    """
    Finds the value of n < ceiling for which φ(n) is a permutation of n
    and the ratio n / φ(n) is a minimum.
    """
    phi_list = all_totients(ceiling) # Takes about 14 seconds
    min_ratio = (100, 0)
    for n in range(2, ceiling + 1):
        ratio = n / phi_list[n]
        if ratio < min_ratio[0] and sorted(str(n)) == sorted(str(phi_list[n])):
            min_ratio = (ratio, n)
    return min_ratio[1]


def solve(vol=0):
    return totient_permutation(10 ** 7)
