maxx = 10000000 def mkp(x): P = [2] p = [2] n = 3 while n < x: for i in p: if n % i == 0: break else: P.append(n) n += 2 while n > p[-1] ** 2: p.append(P[len(p)]) return P prime = mkp(2 * maxx ** 0.5) p = maxx ** 0.5 pi = 0 for i in xrange(len(prime)): if prime[i] > p: pi = i break q = maxx / p qi = 0 nn, dndn = 0, 1 while pi > 1: pi -= 1 p = prime[pi] q = maxx / p for i in xrange(len(prime) - 1, pi, -1): if prime[i] < q: qi = i + 1 break while qi > pi: qi -= 1 q = prime[qi] n = p * q if n > maxx: continue dn = p + q - 1 if n * dndn > nn * dn: sn = str(n) sdn = str(n - dn) if sorted(sn) == sorted(sdn): nn = n dndn = dn break print nn