"""Standalone certificate: no dependencies beyond Python standard library."""
from math import gcd,factorial
from collections import Counter

def rank(a):
    n=len(a);b=list(range(1,n+1));r=0
    for i,x in enumerate(a):
        k=n-i;d=b.index(x,i)-i;r=r*k+d
        w=b[i:];b[i:]=w[d:]+w[:d]
    return r

def flip(a,k):return a[:-k]+a[-k:][::-1]

a=(1,5,11,3,9,2,7,10,6,8,12,4,13);N=factorial(13);r=rank(a)
assert r==139161073 and gcd(r,N)==1
neighbors=set();divisors=Counter()
for i in range(2,14):
    b=flip(a,i)
    for c in [b]+[flip(b,j) for j in range(2,14) if j!=i]:
        t=rank(c);assert gcd(t,N)>1 and t!=r;neighbors.add(t)
        divisors[next(p for p in (2,3,5,7,11,13) if t%p==0)]+=1
assert len(neighbors)==144
b=a;path=[]
for i in (2,4,7):
    b=flip(b,i);path.append((i,rank(b),gcd(rank(b),N)))
assert rank(b)==139161721 and gcd(rank(b),N)==1
print('n=13, rank=',r,'isolated in P_n^2[A_n], 144 neighbors checked')
print('Smallest prime divisor counts:',dict(sorted(divisors.items())))
print('Escape (flip,rank,gcd):',path)
