"""Distance exacte de sortie dans un bloc (les intermédiaires sont libres)."""
from collections import deque
from functools import lru_cache
from math import factorial, gcd
import sources
from roues import rank, unrank


@lru_cache(maxsize=4096)
def layers(k, s):
    start = unrank(k, s)
    seen = {start}
    queue = deque([(start, 0)])
    by_distance = []
    while queue:
        word, d = queue.popleft()
        if len(by_distance) <= d:
            by_distance.append([])
        by_distance[d].append(rank(word))
        for size in range(2, k+1):
            other = word[:-size] + word[-size:][::-1]
            if other not in seen:
                seen.add(other)
                queue.append((other, d+1))
    return by_distance


def exit_depth(modulus, k, r):
    """modulus a les mêmes diviseurs premiers que n!, r est un rang admissible."""
    if gcd(r, modulus) != 1:
        raise ValueError("rang non admissible")
    b = factorial(k)
    start = r-r%b
    for depth, layer in enumerate(layers(k, r%b)[1:], 1):
        if any(gcd(start+t, modulus) == 1 for t in layer):
            return depth
    return None


if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("n", type=int)
    parser.add_argument("k", type=int)
    parser.add_argument("rang", type=int)
    args = parser.parse_args()
    if not (2 <= args.k <= min(args.n, 7) and 0 <= args.rang < factorial(args.n)):
        parser.error("2 <= k <= min(n,7), rang dans [0,n!)")
    print(exit_depth(factorial(args.n), args.k, args.rang))
